vendredi 15 février 2019

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 string stream 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
This is what the text file looks like

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();

Aucun commentaire:

Enregistrer un commentaire