web analytics

How to clear the buffer for a stringstream variable in C++?

Options

davegate 143 - 921
@2015-12-16 11:22:42

Copy the try to run the following C++ code, and guess what thr output will be.

#include <iostream>
#include <sstream>
using namespace std;

int main()
{
 stringstream ss;
 
 ss << "Hello ";
 
 cout << ss.str();
 
 ss << "World!";
 
 cout << ss.str() << endl;
 
 return 0;

}

If you think the output will be:

Hello World!

Then you are wrong, the actual output is:

Hello Hello World!

To get the result you expect, you have to clear the buffer of the stringstream variable, the following code shows you how to do that:

#include <iostream>
#include <sstream>
using namespace std;

int main()
{
 stringstream ss;
 
 ss << "Hello ";
 
 cout << ss.str();
 
 ss.str("");
 
 ss << "World!";
 
 cout << ss.str() << endl;
 
 return 0;

}

stringstream::str

string str ( ) const;

void str ( const string & s ); 

The first version returns a copy of the string object currently associated with the string stream buffer.

The second syntax copies the content of string s to the string object associated with the string stream buffer.

Comments

You must Sign In to comment on this topic.


© 2024 Digcode.com