【问题标题】:C++ - repeatedly using istringstreamC++ - 重复使用 istringstream
【发布时间】:2011-02-15 13:47:08
【问题描述】:

我有一个代码用于读取在线存储的浮点数文件,如下所示:“3.34|2.3409|1.0001|...|1.1|”。我想使用 istringstream 阅读它们,但它并没有像我预期的那样工作:

  string row;
  string strNum;

  istringstream separate;  // textovy stream pro konverzi

   while ( getline(file,row) ) {
      separate.str(row);  // = HERE is PROBLEM =
      while( getline(separate, strNum, '|') )  { // using delimiter
        flNum = strToFl(strNum);    // my conversion
        insertIntoMatrix(i,j,flNum);  // some function
        j++;
      }
      i++;
    }

在标记点,仅第一次将行复制到单独的流中。在下一次迭代中它不起作用,它什么也不做。我希望可以在每次迭代中不构造新的 istringstream 对象的情况下使用更多次。

【问题讨论】:

    标签: c++ string split istringstream


    【解决方案1】:

    将行设置到字符串流之后...

    separate.str(row);
    

    ...通过调用重置它

    separate.clear();
    

    这将清除在上一次迭代中设置或通过设置字符串设置的任何 iostate 标志。 http://www.cplusplus.com/reference/iostream/ios/clear/

    【讨论】:

    • 非常感谢。这是我在许多代码中遗漏的非常重要的信息;)
    • 它真的需要在之后吗?我想你也可以先清除它。
    【解决方案2】:

    您需要在separate.str(row) 之后添加separate.clear(); 行以清除状态位,否则eofbit 被设置并且后续读取失败。

    【讨论】:

      猜你喜欢
      • 2019-04-28
      • 1970-01-01
      • 1970-01-01
      • 2017-08-23
      • 1970-01-01
      • 1970-01-01
      • 2013-05-11
      相关资源
      最近更新 更多