2015-01-31 2 views
1

파일에서 항목 목록을 읽은 다음 벡터에 저장하려고합니다. 문제는 내 코드가 벡터에 마지막 항목을 두 번 더하고 프로그램이 끝났음에도 불구하고 파일을 계속 읽는 이유가 확실하지 않다는 것입니다.파일에서 데이터 읽기 및 벡터에 저장

다음은 텍스트 파일의 내용입니다. 벡터의 내용을 표시하면 "오렌지"선이 두 번 나타납니다.

사과 파운드-10 2

오렌지 파운드 - 5 6

여기 // 이것은 전형적인 파일

while (!inputFile.fail()) 
{ 

    //Extract the line from the list 
    getline(inputFile,item_name,'-'); 
    getline(inputFile,item_unit,'-'); 
    inputFile >> item_amount; 
    inputFile >> item_price; 

    //Create an instance of the item object 
    Item New_Item(item_name, item_unit, item_amount,item_price); 

    //Push it to the list vector 
    list.push_back(New_Item); 
} 

//Close the file 
inputFile.close(); 

답변

1

문제는 파일에서 더 많은 데이터를 읽으 려 할 때까지 "실패"플래그가 설정되지 않는다는 것입니다. 이 학습 운동을 위해, 당신이 그것을 어떻게해야, 아직 >> 연산자를 배울하지 않은 경우

for (;;) { 
    //Extract the line from the list 
    getline(inputFile,item_name,'-'); 
    getline(inputFile,item_unit,'-'); 
    inputFile >> item_amount; 
    inputFile >> item_price; 
    if (inputFile.fail()) break; 
    //Create an instance of the item object 
    Item New_Item(item_name, item_unit, item_amount,item_price); 
    //Push it to the list vector 
    list.push_back(New_Item); 
} 

: 다음은이를 고정하는 빠른 방법입니다. 그렇지 않으면 operator>> 접근 방식이 더 좋습니다.

2

에 목록의 내용을 읽어 코드입니다 anti-pattern의 증상은 while (!infile.fail())입니다.

I 그 타입 구조체 과부하 operator>>을 정의하려는

:

std::ifstream inputFile("fileNameHere"); 

std::vector<New_Item> items { std::istream_iterator<Item>(inputFile), 
           std::istream_iterator<Item>() }; 

[I가 list에서 vector로 변경됨 사소한에서 데이터 경계를 읽고 정의한 것과

struct item { 
    std::string name; 
    std::string unit; 
    int amount; 
    int price; 
}; 

std::istream &std::operator>>(std::istream &is, item &i) { 
    getline(is, i.name, '-'); 
    getline(is, i.unit, '-'); 
    is >> i.amount; 
    return is >> i.price; 
} 

왜냐하면, 글쎄, 당신은 정말로 원하지 않는다. list. 다시 되돌릴 수는 있지만 가능하지는 않습니다.]

관련 문제