I am new to C++ and still juggling with stringstream. I have written a small piece of code which doesn't give required output The code is as follows:
#include "iostream"
#include "sstream"
using namespace std;
int main ()
{
string xyz;
cout << "Initial xyz : " << xyz << endl;
stringstream s1 ( xyz );
s1 << "Hello";
cout << "Final xyz : " << xyz << endl;
}
Output:
Initial xyz :
Fin开发者_开发知识库al xyz :
My understanding is stringstream works as a wrapper around a string object.Therefore once stringstream has been initialized with a string object, any write operation on the stream will affect the underlying string object.So when I write "Hello" to stream and print the string xyz, it should display "Hello". But this clearly does not seem to be the case. Can someone please tell me where am I wrong and how can I manipulate the underlying string using stringstream? Thanks in advance ! Vimal
It is not wrapper. It allocates own string object inside. But you can assign your xyz:
s1 << "Hello";
xyz = s1.str();
Stringstream is a wrapper around a string object - it's own internal string object. You cannot set it to wrap an external string, as that would be incredibly unsafe.
It's not a wrapper for a string, it's a stream. ( just like you can talk about an audio stream)
It allows you to manipulate a virtual string almost the same way you manipulate a file. By adding data sequencially, or reading data sequentially.
Here is the cplusplus reference for stringstream
And when you want to use the constructed string, you call str() on it.
By the way, one of the common use of stringstream is to use it as a string converter. It should be prefered to all atoi itoa stuffs.
Thanks a lot for your prompt replies. My understanding now is : -> If a string needs to be treated as a stream ( example for ease of extraction ), then create a new stringstream object and initialize it with the string.The stream will copy the contents of the string into its own internal string.Any subsequent write operation on the stream will not affect the original string.
-> However if an entirely new string need to be created, just create a blank stringstream object without initializing it with a string object.Write to the stream and once done, just use the str() method of stringstream to copy the contents of stream's string to your own string. I tried this as follows and it is working fine.
#include "iostream"
#include "sstream"
using namespace std;
int main ()
{
stringstream s1;
s1 << "Hello";
string xyz = s1.str();
cout << "Final xyz : " << xyz << endl;
}
In any case, my original query has been satisfactorily solved. Thanks once again.
精彩评论