Demonstrating ostringstream

Figure 19.11 demonstrates an ostringstream object. The program creates ostringstream object outputString (line 10) and uses the stream insertion operator to output a series of strings and numerical values to the object.


 1   // Fig. 19.11: Fig19_11.cpp
 2   // Using an ostringstream object.
 3   #include <iostream>
 4   #include <string>
 5   #include <sstream> // header for string stream processing     
 6   using namespace std;
 7
 8   int main()
 9   {
10      ostringstream outputString; // create ostringstream instance
11
12      string string1( "Output of several data types " );
13      string string2( "to an ostringstream object:" );
14      string string3( "         double: " );
15      string string4( "            int: " );
16      string string5( " address of int: " );
17
18      double double1 = 123.4567;
19      int integer = 22;
20
21      // output strings, double and int to ostringstream outputString
22      outputString << string1 << string2 << string3 << double1       
23         << string4 << integer << string5 << &integer;               
24
25      // call str to obtain string contents of the ostringstream
26      cout << "outputString contains: " << outputString.str(); 
27
28      // add additional characters and call str to output string
29      outputString << " more characters added";                
30      cout << " after additional stream insertions, "
31         << "outputString contains: " << outputString.str() << endl;
32   } // end main


outputString contains:
Output of several data types to an ostringstream object:
        double: 123.457
           int: 22
address of int: 0012F540

after additional stream insertions,
outputString contains:
Output of several data types to an ostringstream object:
        double: 123.457
           int: 22
address of int: 0012F540
more characters added


Fig. 19.11. Using an ostringstream object.

Lines 22–23 output string string1, string string2, string string3, double double1, string string4, int integer, string string5 and the address of int integer—all to outputString in memory. Line 26 uses the stream insertion operator and the call outputString.str() to display a copy of the string created in lines 22–23. Line 29 demonstrates that more data can be appended to the string in memory by simply issuing another stream insertion operation to outputString. Lines 30–31 display string outputString after appending additional characters.

An istringstream object inputs data from a string in memory to program variables. Data is stored in an istringstream object as characters. Input from the istringstream object works identically to input from any file. The end of the string is interpreted by the istringstream object as end-of-file.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset