c++ - Reading data from a file and storing it into a vector -
i'm trying read list of items from file , store them vector. issue code adding last item vector twice , i'm not sure why keeps reading file though program has reached end.
here's what's in text file. "oranges" line appears twice when display contents of vector.
apples-pounds-10 2
oranges-pounds-5 6
here's code //read contents of list file
while (!inputfile.fail()) { //extract line list getline(inputfile,item_name,'-'); getline(inputfile,item_unit,'-'); inputfile >> item_amount; inputfile >> item_price; //create instance of item object item new_item(item_name, item_unit, item_amount,item_price); //push list vector list.push_back(new_item); } //close file inputfile.close();
the problem "fail" flag not set until make attempt @ reading more data file. here quick way of fixing this:
for (;;) { //extract line list getline(inputfile,item_name,'-'); getline(inputfile,item_unit,'-'); inputfile >> item_amount; inputfile >> item_price; if (inputfile.fail()) break; //create instance of item object item new_item(item_name, item_unit, item_amount,item_price); //push list vector list.push_back(new_item); }
if learning exercise, , have not learn >>
operator yet, should it. otherwise, operator>>
approach better.
Comments
Post a Comment