vaprvsapr
vaprvsapr

Reputation: 1

Why do I need clear() stringstream after reading from it in a function?

Why should I write ss.clear() in function Read() to be able to write to stringstream ss again?

#include <iostream>
#include <sstream>
using namespace std;

void Read(istream& ss, string& s)
{
    while(getline(ss, s)){
        cout << s << endl;
    }
    ss.clear();
}

int main()
{
    stringstream ss;
    string s;
    ss << "A\nB\n";
    Read(ss, s);
    ss << "C\n";
    Read(ss, s);
}

If ss.clear() is commented, the third line is not written to cout.

Upvotes: 0

Views: 214

Answers (1)

463035818_is_not_an_ai
463035818_is_not_an_ai

Reputation: 122516

When you call

ss << "A\nB\n";
Read(ss, s);

The first call to getline extracts A, the second extracts B, and it is important to understand that you can only know that you are at the end of the stream after getline has been called once more. The third call to getline fails, there is no 3rd line in the stream, and the loop stops. From cppreference:

If no characters were extracted for whatever reason (not even the discarded delimiter), getline sets failbit and returns.

Once the failbit is set, the stream cant be used to extract more. Calling clear resets the error bits so you can continue using the stream.

Upvotes: 4

Related Questions