qiubit
qiubit

Reputation: 4816

What will happen if I won't clear stringstream?

I was doing a graph problem in TopCoder and somehow my program kept outputting wrong answer even though I thought everything should be ok with it. I spent hours and hours looking for error in my logic and, as it turned out, the problem was lying somewhere else. Here is a snippet of code I've got a question about:

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

As you can see in the comments I managed to solve the problem. But I can't see why do I need to clear those stringstreams. What exactly is happening if I'm not doing that?

Upvotes: 3

Views: 216

Answers (1)

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385194

Once you've extracted all data from the stream and attempted to read "just one more character!" (which the in-built extraction to int will try to do, to find out whether there are more digits to read), its eof bit is set.

You are re-using the stream by changing its buffer's "contents", which is fine, but you need to reset that eof bit too. That's what .clear() does.

To re-use a stringstream in general:

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

(In your case you're directly replacing the buffer with your new data, later on, using .str("newText!"), instead of writing .str(""), and that's fine.)

It's confusing because a function like clear sounds like it's going to clear the data, but it doesn't.

Upvotes: 6

Related Questions