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:
#include <iostream> // for accessing the console
#include <sstream>
#include <string>
using namespace std;
int main()
{
string input;
getline(cin, input);
stringstream memString(input, ios_base::in);
// == istringstream memString(input, ios_base::in);
double summ = 0;
double temp;
while (memString >> temp)
{
summ+= temp;
}
cout<< summ << endl;
return 1;
}
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.
No wonder the program works flawlessly:
1.234 2.48 3.206
6.92
Press any key to continue . . .
Next: For Output >>
More C++ Articles
More By Gabor Bernat