简体   繁体   中英

“Peek ahead” to check whether the next call to getline(file,line) will return false - without actually calling it i.e. without consuming the line

So we usually do someth like

std::ifstream file("file");
std::string line;
bool ret = getline(file,line);

and the "ret" bool tells us whether the line was found.

But how can I find beforehand whether the next call to "getline()" will definitely return false? In other words, how can I check whether I have already reached the EOF, without really having to call "getline()" to confirm it?

The reason I want to do this is that I have a situation like this:

while(getline(file,line))
{
  //code
  //i want to do some "final" thing right here in this loop, for the last line.
}

You could use std::istream::peek

Reads and returns the next character without extracting it, ie leaving it as the next character to be extracted from the stream.

Will return EOF , if end is reached.

getline actually returns a reference to the ostream, which will only cast to false once eof has been reached or the stream goes bad, which cannot be predicted. Therefore, it depends on your situation and whether you want to handle both eof and bad streams.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM