String streams

Just as you can read input data from files and write output data to files, you can also read 'input' from strings and write 'output' into strings.

Both are done using stringstream objects, provided in the sstream library.

Reading input from strings

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

int main()
{
   // suppose we have a bunch of data stored in a string
   string text = "123.5  blah  x  13";

   // declare an istringstream object that we'll use for
   //    reading from the string
   istringstream myInput;

   // copy the string data into the istringstream variable
   //    using the str method
   myInput.str(text);

   // now we can use the istringstream variable the same
   //    way we would usually use cin
   
   // declare some data to store the pieces of data we
   //    pull from the string
   float f;
   string s;
   char c;
   int i;

   // do some reads
   myInput >> f;  // f now contains 123.5
   myInput >> s;  // f now contains blah
   myInput >> c;  // f now contains x
   myInput >> i;  // f now contains 13

   // check out the results
   cout << f << s << c << i << endl;

}

Writing output to strings

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

int main()
{
   // declare an ostringstream object to write to
   ostringstream myOutput;

   // write a bunch of formatted data to the object
   myOutput << setw(4) << "1" << endl;
   myOutput << "blah blah blah";
   myOutput << fixed << setprecision(2) << setw(6) << (12.4567) << endl;

   // now extract the data as a string
   string s = myOutput.str();

   // try printing out the string just to check
   cout << s;
}