I struggle to understand the different behaviours of stringstream from the following code. Can someone shed a light on how stream internally works?
int main(){
string str = "123";
stringstream ss(str);
cout << ss.str() <<endl;
ss << str;
cout << ss.str() <<endl;
}
output:
123
123
int main(){
string str = "123";
stringstream ss;
ss << str;
cout << ss.str() <<endl;
ss << str;
cout << ss.str() <<endl;
}
output:
123
123123
A stringstream is an iostream object that uses a std::string as a backing store. An ostringstream writes to a std::string . An istringstream reads from a std::string . You read & write from & to an istringstream or ostringstream using << and >> , just like any other iostream object.
string stream is slow. Quite very slow. If you are writing anything performance critical that acts on large data sets ( say loading assets after a level change during a game ) do not use string streams.
The StringStream class in C++ is derived from the iostream class. Similar to other stream-based classes, StringStream in C++ allows performing insertion, extraction, and other operations. It is commonly used in parsing inputs and converting strings to numbers, and vice-versa.
To use stringstream class in the C++ program, we have to use the header <sstream>. For Example, the code to extract an integer from the string would be: string mystr(“2019”); int myInt; stringstream (mystr)>>myInt; Here we declare a string object with value “2019” and an int object “myInt”.
It's because the actual write position isn't updated, so when you in the first example do
ss << str;
you overwrite the current string.
Use the flag std::ios_base::ate
to the constructor of the string stream
std::stringstream ss(str,
std::ios_base::in | std::ios_base::out | std::ios_base::ate);
to position the read/write pointers at the end.
See the example in this reference.
And it's like that for all streams, when you open a file stream the positions are also at the start.
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