开发者

When do I stop reading from a file?

开发者 https://www.devze.com 2023-01-29 16:45 出处:网络
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

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
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号