c++ - Reading in data from a text file using while loop -
this question has answer here:
so reading in data text file in vector using while loop.
originally had code set way :
iftream infile; while(infile) // or if while(!infile.eof()) { infile>>data; vector1.push_back(data); //adding data in vector }
- caused 1 small problem read in last item in text file twice reason.
but if have code set way works fine :
iftream infile; while(infile>>data) { vector1.push_back(data); //adding data in vector }
why first code reads in last item twice?
it looks data
structure not entirely aligned within file, i.e. when program tries read last fragment, hasn't reached end of file yet, there isn't enough data read. infile >> data
fails, means contents of data
haven't been changed, , therefore add vector again.
in second case, check result of read, therefore don't attempt push data
contents when wasn't read properly.
Comments
Post a Comment