为什么stringstream会停止接收字符串? [C ++]

问题描述 投票:3回答:1

我正在尝试实现一种从文本文件中读取输入的方法,以便更轻松地加载不同的坐标集,但是我遇到了一个我不明白的错误,我的stringstream对象将在其中一行之后停止接收字符串格式不对。

在我的输出中,你可以看到字符串在打印出来时仍然完好无损,然后它被放入下一行的stringstream,但是在一个格式错误的字符串之后,stringstream在我打印出来时停止包含任何内容。

这里发生了什么?

输出:

image

这是文本文件的样子:

image

方法代码:

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();
c++ string c++11 ifstream stringstream
1个回答
7
投票

由于流无法读取整数时进入错误状态,因此您需要清除错误状态。要做到这一点:

ss.clear();

更容易做的就是将stringstream的定义移动到循环中:

istringstream ss(line);
if(ss >> x >> comma >> y >> comma >> direction)
    // ...
© www.soinside.com 2019 - 2024. All rights reserved.