Search code examples
c++stringc++11ifstreamstringstream

Why does stringstream stop receiving strings? [C++]


I'm trying to implement a way of reading inputs from text files to load different sets of coordinates more easily, but I've come across a bug I don't understand, where my stringstream object will stop receiving strings once one of the lines is ill-formatted.

In my output, you can see that the string is still intact when it's printed out, and then it's put into the stringstream on the very next line, but after one ill-formatted string, the stringstream stops containing anything when I print it out.

What's going on here?

Output:

image

This is what the text file looks like:

image

Method code:

ifstream pathfile(p.string());
cout << "Path file opened successfully.\n\n";

string line;
stringstream ss;
int x, y;
char comma,direction;

//Iterate all lines in the file
while(getline(pathfile,line)){
  //remove all spaces from line
  line.erase(remove(line.begin(), line.end(), ' '), line.end());
  //skip comments and blank lines
  if(line.c_str()[0] == '#' || line.empty()) continue;
  //parse remaining lines
  ss.str(string()); //clear stringstream
  cout <<"LINE: "<<line<<endl;
  ss << line;
  cout <<"SS: "<<ss.str()<<endl;

  if(ss >> x >> comma >> y >> comma >> direction)
    cout << "X: "<<x<<"  Y: "<<y<<"  D: "<<direction;
  else{
    cout << "Ill-formatted line: ";
  }
  printf(" |  %s\n\n", line.c_str());
}
pathfile.close();

Solution

  • Since the stream enters an error state when it fails to read an integer, you will need to clear the error state. To do that:

    ss.clear();
    

    The much easier thing to do is just move the definition of the stringstream into the loop:

    istringstream ss(line);
    if(ss >> x >> comma >> y >> comma >> direction)
        // ...