如果我不清楚串流会怎么样?

时间:2014-12-23 11:19:02

标签: c++ stringstream

我在TopCoder中做了一个图形问题,不知怎的,我的程序仍然输出错误的答案,即使我认为一切都应该没问题。我花了几个小时的时间在我的逻辑中寻找错误,事实证明,问题在于其他地方。这是一段代码,我有一个问题:

int x, y;
stringstream ssx;
stringstream ssy;
for (int i = 0; i < connects.size(); i++){
    neighbours.push_back(vector<int> ());
    edges_cost.push_back(vector<int> ());
    ssx.str(connects[i]);
    ssy.str(costs[i]);
    while (ssx >> x && ssy >> y){
        neighbours[i].push_back(x);
        edges_cost[i].push_back(y);
    }
    // The problem lied here. Apparently without these 2 lines
    // the program outputs wrong answer. Why?
    ssx.clear();
    ssy.clear();
}

正如您在评论中看到的那样,我设法解决了这个问题。但我不知道为什么我需要清除那些串流。如果我不这样做,到底发生了什么?

1 个答案:

答案 0 :(得分:6)

从流中提取所有数据并尝试阅读“只需一个字符!” (对于int的内置提取将尝试执行,以确定是否有更多数字要读取),其eof位已设置。

您正在通过更改其缓冲区的“内容”来重新使用该流,这很好,但您也需要重置该eof位。这就是.clear()所做的。

通常重复使用字符串流:

ss.str("");  // clears data
ss.clear();  // clears all error flag bits

(在您的情况下,您将使用.str("newText!")直接用新数据替换缓冲区,而不是写.str(""),这很好。)

这很令人困惑,因为像clear 这样的函数听起来像它会清除数据,但事实并非如此。

相关问题