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

标签 c++ string c++11 ifstream stringstream

我正在尝试实现一种从文本文件读取输入以更轻松地加载不同坐标集的方法,但我遇到了一个我不明白的错误,其中我的 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();

最佳答案

由于流在读取整数失败时进入错误状态,因此您需要清除错误状态。为此:

ss.clear();

更简单的做法是将 stringstream 的定义移动到循环中:

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

关于c++ - 为什么 stringstream 停止接收字符串? [C++],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54718316/

相关文章:

C++ 标准库 - std::setenv 与 setenv

c++ - 类型(变量)与(类型)变量

asp.net - 带按钮的私有(private)字符串的 ViewState

c++ - ISO C++ 禁止声明 .. 没有设置 --std=c++0x 的类型

c++ - 在库析构函数之前调用的静态变量析构函数

python - 确定 OR 正则表达式的哪个片段与字符串匹配

c++ - **字符串': ambiguous symbol**

c++ - 为什么auto不能作为函数声明的返回类型

c++ - 在没有分配器实例的情况下,是否有一种简单的方法在 C++ 中默认构造一个泛型类型?

c++ - gcc 的自动向量化消息是什么意思?