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 (>>)?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With