Some Noob Student
Some Noob Student

Reputation: 14594

Can extraction operator (>>) overwrite a variable?

I wrote the following test code:

int main(int argc, char* argv[]) {
    stringstream ss;
    int num;

    ss << "54321";
    ss >> num;
    ss.str("");
    ss << "12345";
    ss >> num;

    fprintf(stderr, "%d\n", num);
}

To my surprise, the result was 54321. How do you correctly overwrite a variable using the extraction operator (>>)?

Upvotes: 2

Views: 224

Answers (2)

jrok
jrok

Reputation: 55415

After the first extraction, you reached the end of stream, so the eofbit got set and the second extraction failed.

int main(int argc, char* argv[]) {
    stringstream ss;
    int num;

    ss << "54321";
    ss >> num;

    // eofbit was set above,
    // we need to clear it
    ss.clear();

    ss.str("");
    ss << "12345";
    ss >> num;

    fprintf(stderr, "%d\n", num);
}

Call clear() member function before you attempt the second extraction. The second problem is the position of the internal get pointer, which won't get reset automatically. Use seekg() to set it.

EDIT: the striked stuff isn't neccesary, explained here.

Upvotes: 8

Dietmar K&#252;hl
Dietmar K&#252;hl

Reputation: 153945

When the stream reaches the end of the stream, std::ios_base::eofbit gets set. Before trying to extract any date, the extraction checks if any state flag is set and, if so, it doesn't do anything and your extraction fails:

std::stringstream ss;
ss << "54321";
ss >> num; // sets eof:
std::cout << "eof: " << ss.eof() << "\n";

To have the stream do anything once any of the state flags gets set, you need to first clear the flags:

ss.clear();
ss << "12345";
if (ss >> num) {
    std::cout << "num=" << num << "\n";
}
else {
    std::cout << "failed to extract a value\n";
}

Personally, I generally don't use the output operators to set the string stream's content. Instead, I'm normally using the str() member:

std::ostringstream out; // note: this is just an output string stream
...
out.clear();            // the clear is still needed
out.str("12345");

Upvotes: 4

Related Questions