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
eofbitgot set and the second extraction failed.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. Useseekg()to set it.EDIT: the striked stuff isn’t neccesary, explained here.