# C++ Notes: String Streams

Like files, strings are a sequence of characters. C++ provides a way to associate an I/O stream with a string. Here are some common uses for string streams.

1. Localizing errors in input. It is common to process one line at a time. The standard input streams proceed to the next line if there are insufficient values on one line. Also, an error in the input may make error recovery difficult. The solution is to read the input one line at a time into a string. Then "read" that string using a string stream.
2. Reading one of two types. Suppose you don't know what type the next input element is - it's either an int or a name. Solution: read it into a string, then try reading from the string as an int. If that fails assume it's a name.

   Use this to read to a sentinal value. For example, let's say you are reading integers until a certain value. But what value can you use to stop the input? Why not use "STOP" or some other string. Well, you can't do this easily while reading ints from `cin`, but you can read from `cin` into a string, compare that string to "STOP", and if it doesn't match, "read" from the string with a string stream as an integer.

3. Converting internal values to their external representations. Sometimes you want a character representation of data in memory. The best facilities for formatting data (eg, numbers) are the output stream facilities. You can create an output stream that goes into a string to make use of the stream fomatting.

## String stream input - `istringstream`

String streams support all the normal iostream capabilities. There are only two additional things you need.

1. Input string streams must be declared `istringstream`.
2. The string value to read is set with `str()`.

Here is a simple example.

    #include <iostream>
    #include <sstream>
    using namespace std;
    . . .
    int a, b;
    string s = "34 22";
    istringstream ins; // Declare an input string stream.
    . . .
    ins.str(s);        // Specify string to read.
    ins >> a >> b;     // Reads the integers from the string.

## String stream output - `ostringstream`

Simlarly, there are only a couple of things you need to know to use output string streams.

1. Output string streams must be declared `ostringstream`.
2. The string value is obtained from the stream with `str()`.

Here is a simple example that puts the character value of the square root of 2 into a string.

    #include <iostream>
    #include <sstream>
    using namespace std;
    . . .
    ostringstream outs;  // Declare an output string stream.
    . . .
    outs << sqrt(2.0);   // Convert value into a string.
    s = outs.str();      // Get the created string from the output stream.