【问题标题】:Why does stringstream stop receiving strings? [C++]为什么 stringstream 停止接收字符串? [C++]
【发布时间】:2019-02-15 23:24:11
【问题描述】:

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

在我的输出中,您可以看到打印出来的字符串仍然完好无损,然后将其放入下一行的stringstream,但在一个格式错误的字符串之后,stringstream 停止包含我打印出来的任何东西。

这里发生了什么?

输出:

这是文本文件的样子:

方法代码:

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

【问题讨论】:

  • line.c_str()[0]...嗯,为什么不line[0]?你应该检查它是否是一个空字符串 before 检查,而不是之后。

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


【解决方案1】:

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

ss.clear();

更简单的做法是将字符串流的定义移到循环中:

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

【讨论】:

  • 请注意效率损失。因此,如果您需要,请查看 .clear().str("")
  • 嗯 @sehe 我认为您应该在声称效率之前尝试基准测试。
  • 我应该说潜在的效率损失。但是,在 stringstream 构造的情况下,我经常测量它以产生显着差异。不过,在过去 4 年中并非如此,并且一些编译器在内置原语和省略分配方面取得了长足的进步。
猜你喜欢
  • 1970-01-01
  • 2010-12-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-03-12
相关资源
最近更新 更多