fredoverflow
fredoverflow

Reputation: 263118

When do I stop reading from a file?

Does some_file.good() return false after reading the last entry from the file, or after attempting to read beyond that? That is, should I write

while (input.good())
{
    getline(input, line);
    // ...process
}

or

getline(input, line);
while (input.good())
{
    // ...process
    getline(input, line);
}

?

Upvotes: 2

Views: 2502

Answers (2)

Rune Aamodt
Rune Aamodt

Reputation: 2611

As already suggested, getline returns zero when there are no more lines. Also the method eof() returns true if the EOF flag is set (i.e. end of file reached on the stream):

if(input.eof())
{
// end of file
}

Upvotes: 0

Nim
Nim

Reputation: 33655

Attempting to read beyond that...

You could try:

while(getline(input, line))
{
// do stuff with line
}

Should add, that stream implements operator!, which checks the flags that you normally would. The return from getline is the input stream, but because of the operator, the flags are checked.

Upvotes: 9

Related Questions