为什么 stringstream 有这种行为? [英] Why stringstream has this behavior?

查看:41
本文介绍了为什么 stringstream 有这种行为?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个这样的代码,关于字符串流.我发现了一个奇怪的行为:

I have a code like this, concerning stringstream. I found a strange behavior:

#include <iostream>
#include <fstream>
#include <sstream>

using namespace std;

int main()
{
  int     p, q;
  fstream file;
  string  str;
  stringstream sstr;

  file.open("file.txt", ios::in);
  if(file.is_open()) {
    while(getline(file, str)) {
      sstr << str;
      sstr >> p >> q;
      cout << p << ' ' << q << endl;
      sstr.str("");
    }
  }
  file.close();

  return 0;
}

假设我有 file.txt

Suppose I have file.txt as

4 5

0 2

在第一行的 5 和第二行的 2 之后返回.程序给了我:

with return after 5 in the first line and 2 in the second line. The program gives me:

4 5

4 5

这意味着 pq 没有正确分配.但是我每次都检查 sstr.str() 并获取该行的正确字符串.

which means p and q are not correctly assigned. But I checked that each time sstr.str() with get the correct string of the line.

为什么 stringstream 有这样的行为?

Why stringstream has a behaviour like this?

推荐答案

流在读取第二个整数后处于非良好状态,因此您必须在恢复之前重置其错误状态.

The stream is in a non-good state after reading the second integer, so you have to reset its error state before resuming.

你真正的错误是没有检查输入操作的返回值,否则你会立即发现!

Your real mistake was to not check the return value of the input operations, or you would have caught this immediately!

更简单的解决方案可能是不要尝试重复使用相同的流,而是每轮重新使用它:

The simpler solution may be to not try to reuse the same stream, but instead make it anew each round:

for (std::string line; std::getline(file, line); )
{
    std::istringstream iss(line);
    if (!(iss >> p >> q >> std::ws) || !iss.eof())
    {
        // parse error!
        continue;
    }
    std::cout << "Input: [" << p << ", " << q << "]\n";
}

这篇关于为什么 stringstream 有这种行为?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆