Variety is the spice of life; if you could see the same things each day, drink the same coffee, meet the same people, eat the same things, life would be absolutely boring. The drawback of this, on the other hand, is that coordinating such variety can be a big challenge. Copied from the multiplicity in our world, we have a significant diversity of types within the C++ programming world. This is not always a good thing. This article will explain how to tackle this challenge with help from streams and the STL class.
Using Stringstreams in C++ - Using It for Input (Page 2 of 4 )
You will find the class defined/declared inside the stringstream header; thus, to use it, first you need to include the sstream, while adding the "using namespace std;" line will surely make it more enjoyable to write by letting you write less and produce more. There are three types of stringstream. First, we have one used only for output, one used with only input, and one combining the "muscles" of both input and output. Declare them as follows:
ostringstream outMemStream; // output
istringstream inMemStream; // input
stringstream memoryStream; // both in and out
If UNICODE is your daily bread, then you only need to append a "w" char to the beginning (prefix) to form the wide character counterparts of the upper ones, namely the wostringstream (for out), wistreangstream (for in) and wstringstream (for both).
Now let us look for some way to use this. Suppose you want to read a whole line of integers, and once that is done, calculate their sum. Reading in one member after the other is not a good solution, as the cin will stop for each white space (including the new line as well).
If we are talking about line reading, the most useful function remains the getline, so we should call it for help somehow. We may just read in a line, but how will we extract the numbers from it? This is where the stringstream comes in.
Each stringstream is in fact a stream if, resulting in a couple of advantages. For instance, you can take a stringstream and open it only for output. Moreover, there is another definition of the constructor that allows you to pass on a string as the first argument; this will fill the content of the string, the buffer.
This is perfect for us. Just get the input and put it inside the stream; after that, read it out of the stream one by one and total it. This gives us something close to this:
In fact, once you construct the stream it will behave just like a file stream, with the exception that this is automatically constructed inside the memory poll. It's a perfect solution for when you need a temporary container/buffer in which to store your data, and you can also extract it from there later on.