What happens if I don't clear the line?

I was doing a graph problem in TopCoder and somehow my program kept outputting the wrong answer even though I thought it should be okay with it. I spent hours and hours looking for errors in my logic and, as it turned out, the problem lay somewhere else. Here is the code snippet I have a question for:

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 was able to resolve the issue. But I don't understand why I need to clear these lines. What exactly happens if I don't?

+3


source to share


1 answer


After you've fetched all the data from the stream and tried to read "one more character!" (which will try to inline fetch before int

to see if there are more digits to read) the bit is set eof

.

You reuse the stream by changing its buffer "contents", that's ok, but you need to reset that bit eof

too. What it does .clear()

.

To reuse a string stream altogether:



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

      

(In your case, you are directly replacing the buffer with your new data later, using .str("newText!")

instead of writing .str("")

, which is fine.)

This is confusing because the type function clear

sounds like it cleans up the data, but it isn't.

+6


source







All Articles