Apache C++ Standard Library User's Guide

## 31.1 About String Streams

The iostreams facility supports not only input and output to external devices like files. It also allows in-memory parsing and formatting. Source and sink of the characters read or written becomes a string held somewhere in memory. You use in-memory I/O if the information to be read is already available in the form of a string, or if the formatted result is processed as a string. For example, to interpret the contents of the string `argv[1]` as an integer value, the code might look like this:

    int i;
    std::istringstream strm("...");            //1
    if (strm >> i)                             //2
      // use the value of i

`//1` | The parameter of the input string stream constructor is a string; here a character array is provided as an argument and is implicitly converted to a string.
`//2` | An integer value is extracted from the input string stream.

The inverse operation, taking a value and converting it to characters that are stored in a string, might look like this:

    struct date {
      int day,month,year;
    } today = {8,4,1996};

    std::ostringstream ostr;                                      //1

    ostr << today.month << '-' << today.day <<'-' << today.year;  //2

    if (ostr)
       display(ostr.str());                                       //3

`//1` | An output string stream is created.
`//2` | Values are inserted into the output string stream.
`//3` | The result of the formatting can be retrieved in the form of a string, which is returned by `ostr.str()`.

As with file streams, there are three class templates that implement string streams: basic_istringstream, basic_ostringstream, and basic_stringstream. These are derived from the stream base class templates basic_istream, basic_ostream, and basic_iostream. Therefore they inherit all the functions for formatted input and output described in Chapter 28, as well as the stream state. They also have functions for setting and retrieving the string that serves as source or sink, and constructors that allow you to set the string before construction time. For convenience, there are the regular typedefs `std::istringstream`, `std::ostringstream`, and `std::stringstream,` with`std::wistringstream`, `std::wostringstream`, and `std::wstringstream` for the respective narrow and wide character string streams.

The buffering is implemented by a stream buffer class template, basic_stringbuf.