String Streams

Although we generally think of streams of data flowing into (cin) and out of (cout) our program, we can also use streams to format strings within our program.
Perhaps you want to create a message to be sent to another computer, written to an external device or want to format a string to be passed to/from a function.

The C++ library provides a stream that allows us to do just that. It's called ostringstream. This stream is attached to a string so that we can use the standard insertion operator and manipulators. Note that this code need not check for any kind of string "overflow" since the ostringstream expands as needed.

//------------------------------------ // Sample code for using ostringstream // // DLF 7/14/04 //------------------------------------ #include <iostream> #include <string> #include <iomanip> #include <sstream> // for ostringstream using namespace std; // local function prototype string FormatMessage (int age); int main ( ) { string msg; int age = 42; msg = FormatMessage ( age ); cout << msg << endl; return 0; } //------------------------------------------------------------ // FormatMessage // PreConditions: none // PostCondition: // returns a formatted string that includes the specified age //------------------------------------------------------------ string FormatMessage( int age ) { ostringstream msg; msg << "\nThis is my message\n"; msg << "Mr. Frey is " << setw(6) << age << " years old\n"; // use the str() function to access the C-string in the msg return msg.str( ); } One common programming task is to "parse" a string. To "parse" a string means to examine it one word/letter/symbol at a time. The use of istringstream allows us to use the extraction operator to separate the words. The code below illustrates the basics of parsing using istringstream. //------------------------------------ // Sample code for using 1stringstream // // DLF 7/14/04 //------------------------------------ #include <iostream> #include <string> #include <iomanip> #include <sstream> // for istringstream using namespace std; // local function prototype void PrintWords( string stringToPrint); int main ( ) { PrintWords( "The quick brown fox jumped over the lazy dog"); return 0; } //------------------------------------------------------- // PrintWords // Preconditions: none // Postcondition: the string is printed one word per line //------------------------------------------------------- void PrintWords( string stringToPrint) { // create and initialize the istringstream from the string istringstream inStream( stringToPrint ); string word; while ( inStream >> word ) cout << word << endl; }