Question

Let's say I am trying to read in data line by line from a file called input.txt. There's about 20 lines and each line consists of 3 different data types. If I use this code:

while(!file.eof){ ..... }

Does this function look at only one data type from each line per iteration, or does it look at the all the data types at once for each line per iteration--so the next iteration would look at the next line instead of the next data type?

Many thanks.

Was it helpful?

Solution

.eof() looks at the end of file flag. The flag is set after you run over the end of the file. This is not desirable.

A great blog post on how this works and best practice can be found here.

Basically, use

std::string line;
while(getline(file, line)) { ... }

or

while (file >> some_data) { ... }

as it will notice errors and the end of the file at the correct time and act accordingly.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top