Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

different insert position with stringstream

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

like image 669
pepero Avatar asked Oct 16 '13 10:10

pepero


People also ask

What is the difference between Stringstream and Istringstream?

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.

Is Stringstream slow C++?

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.

What does Stringstream mean in C++?

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.

How do you use Stringstream function?

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”.


1 Answers

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.

like image 119
Some programmer dude Avatar answered Sep 19 '22 18:09

Some programmer dude