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

Popular posts from this blog

PHPMotion implementation - URL based videos (Hosted on separate location) -

c# - Unity IoC Lifetime per HttpRequest for UserStore -

I am trying to solve the error message 'incompatible ranks 0 and 1 in assignment' in a fortran 95 program. -