I am trying to figure out how to reuse a stringstream object without the need to re-allocate the underlying string every time I put something in the stream. I have found this answer which led me to do this:
int main() {
stringstream ss;
int x;
ss << "423";
ss >> x; // x is now 423
ss.clear();
ss.seekg(0);
ss.seekp(0);
ss << "1";
ss >> x; // x is now 123. Instead I want x to be 1.
std::cout << x << std::endl;
}
Unfortunately, this doesn't work since the contents of the string from the first pass are still there (after the first pass the string is "423"
and after the second pass they are "123"
). However, if I add a space right after the second put, things seem to work, like this:
int main() {
stringstream ss;
int x;
ss << "423";
ss >> x; // x is now 423
ss.clear();
ss.seekg(0);
ss.seekp(0);
ss << "1";
ss << " "; // add a space right after the desired value
ss >> x; // x is now 1
std::cout << x << std::endl;
}
After the second pass the string is "1 3"
. I am not very familiar with the I/O library and I would like to know if the above approach is safe, or if it just happens to work in this trivial example, or if there are better solutions out there. Live code here. Thank you!