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);
}
?
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.
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
}
精彩评论