- Learn C++ - https://www.learncpp.com -

23.4 — Stream classes for strings

So far, all of the I/O examples you have seen have been writing to cout or reading from cin. However, there is another set of classes called the stream classes for strings that allow you to use the familiar insertions (<<) and extraction (>>) operators to work with strings. Like istream and ostream, the string streams provide a buffer to hold data. However, unlike cin and cout, these streams are not connected to an I/O channel (such as a keyboard, monitor, etc…). One of the primary uses of string streams is to buffer output for display at a later time, or to process input line-by-line.

There are six stream classes for strings: istringstream (derived from istream), ostringstream (derived from ostream), and stringstream (derived from iostream) are used for reading and writing normal characters width strings. wistringstream, wostringstream, and wstringstream are used for reading and writing wide character strings. To use the stringstreams, you need to #include the sstream header.

There are two ways to get data into a stringstream:

1) Use the insertion (<<) operator:

2) Use the str(string) function to set the value of the buffer:

There are similarly two ways to get data out of a stringstream:

1) Use the str() function to retrieve the results of the buffer:

This prints:

12345 67.89

2) Use the extraction (>>) operator:

This program prints:

12345 - 67.89

Note that the >> operator iterates through the string -- each successive use of >> returns the next extractable value in the stream. On the other hand, str() returns the whole value of the stream, even if the >> has already been used on the stream.

Conversion between strings and numbers

Because the insertion and extraction operators know how to work with all of the basic data types, we can use them in order to convert strings to numbers or vice versa.

First, let’s take a look at converting numbers into a string:

This snippet prints:

12345 67.89

Now let’s convert a numerical string to a number:

This program prints:

12345 67.89

Clearing a stringstream for reuse

There are several ways to empty a stringstream’s buffer.

1) Set it to the empty string using str() with a blank C-style string:

2) Set it to the empty string using str() with a blank std::string object:

Both of these programs produce the following result:


When clearing out a stringstream, it is also generally a good idea to call the clear() function:

clear() resets any error flags that may have been set and returns the stream back to the ok state. We will talk more about the stream state and error flags in the next lesson.

23.5 -- Stream states and input validation [1]
Index [2]
23.3 -- Output with ostream and ios [3]