Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 (>>)?

like image 620
Some Noob Student Avatar asked Apr 19 '26 00:04

Some Noob Student


1 Answers

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.

like image 185
jrok Avatar answered Apr 20 '26 12:04

jrok



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!