### Using the strstream Classes for String Manipulation

You can use the strstream classes to perform formatted input and output to arrays of characters in memory. If you create formatted strings using these classes, your code will be less error-prone than if you use the sprintf() function to create formatted arrays of characters.

Note: For new applications, you may want to consider using the Data Type class IString, rather than strstream, to handle strings. The IString class provides a much broader range of string-handling capabilities than strstream, including the ability to use mathematical operators such as + (to concatenate two strings), = (to copy one string to another), and == (to compare two strings for equality).

You can use the strstream classes to retrieve formatted data from strings and to write formatted data out to strings. This capability can be useful in situations such as the following:

- Your application needs to send formatted data to an external function that will display, store, or print the formatted data. In such cases, your application, rather than the external function, formats the data.
- Your application generates a sequence of formatted outputs, and requires the ability to change earlier outputs as later outputs are determined and placed in the stream, before all outputs are sent to an output device.
- Your application needs to parse the environment string or another string already in memory, as if that string were formatted input.

You can read input from an strstream, or write output to it, using the same I/O operators as for other streams. You can also write a string to a stream, then read that string as a series of formatted inputs. In the following example, the function add() is called with a string argument containing representations of a series of numeric values. The add() function writes this string to a two-way strstream object, then reads double values from that stream, and sums them, until the stream is empty. add() then writes the result to an ostrstream, and returns OutputStream.str(), which is a pointer to the character string contained in the output stream. This character string is then sent to cout by main().

    //    Using the strstream classes to parse an argument list

    #include <strstream.h>
    char* add(char*);

    void main() {
       cout << add("1 27 32.12 518") << endl;
    }

    char* add(char* addString) {
       double value=0,sum=0;
       strstream TwoWayStream;
       ostrstream OutputStream;
       TwoWayStream << addString << endl;
       for (;;) {
          TwoWayStream >> value;
          if (TwoWayStream) sum+=value;
          else break;
          }
       OutputStream << "The sum is: " << sum << "." << ends;
       return OutputStream.str();
    }

This program produces the following output:

    The sum is: 578.12.