std::getline throwing when it hits eof

Viewed 14071

std::getline throws exception when it gets an eof. this is how I am doing.

std::ifstream stream;
stream.exceptions(std::ifstream::failbit|std::ifstream::badbit);
try{
  stream.open(_file.c_str(), std::ios_base::in);
}catch(std::ifstream::failure e){
  std::cout << "Failed to open file " << _file.c_str() << " for reading" << std::endl;
}
while(!stream.eof()){
  std::string buffer = "";
  std::getline(stream, buffer);
  //process buffer
  //I do also need to maintain state while parsing
}

In the above code getline is throwing exception as it gets eof How to handle this situation ?

EDIT

std::string buffer = "";
while(std::getline(stream, buffer)){
    //also causes getline to hit eof and throw
}
2 Answers

As you said, calling getline when the stream is currently positioned on the blank line at the end of the file will set both eofbit (because it reaches the end of file) and failbit (because nothing could be extracted, not even the line delimiter).

So, if you have set the stream to throw exceptions when failbit is set, you get an exception thrown when reading that blank line.

To prevent that, you can peek for the next character on the stream before calling getline:

std::string buffer = "";
while(stream.peek() != EOF && std::getline(stream, buffer)){
    //do something with the buffer
}
Related