Wednesday 17 March 2010

Example of Stringstreams

Here is an example of stringstream that I picked up from here and modified it slightly.




//Program tested on Microsoft Visual Studio 2008 - Zahid Ghadialy
//Simple example of C++ stringstreams

#include<iostream>
#include<sstream>
#include<string>

using namespace
std;

int
main()
{

string input;

cout<< "Please enter some numbers speretaed by space and press enter once done: ";
getline(cin, input);

cout<< "input = " << input << endl;

stringstream memString(input, ios_base::in); //stringstream( string s, openmode mode )

cout<<"memString = " << memString << endl;
cout<<"memString (contents) = " << memString.str() << endl;

double
summ = 0;
double
temp;
while
(memString >> temp)
{

summ+= temp;
}


cout<<"summ = " << summ << endl;

return
0;
}








The output is as follows:


See Also:
C++ Reference on stringstreams
Using Stringstreams in C++
String Stream example
String Streams Constructors

No comments:

Post a Comment