Skip to main content

Section 11.9 String Streams

One final kind of stream is worth discussion: the stringstream. This is a stream that reads from or writes to a string. It can be used as an alternative to std::format for building up a string with data from variables. It also can be used to imitate writing to a file. If we want to test out code that is supposed to write to a file, we can instead have it write to a stringstream and then print out the string that was produced. If the output looks good, we know that if we successfully open a file and write to that instead of the stringstream, our program should work correctly.
The stringstream data type is defined in the <sstream> library. Once we create a variable of type stringstream we can then immediately write to it using << (there is no file to open). Once we are done writing, we can use the .str() method to ask the string stream for the string that was built up:
Listing 11.9.1.
It is also possible to read from a string stream. This is done by using the .str() method to set the string that we want to read from. Once we have set the string, we can use >> to read from it just like we would from a file or the console:
Listing 11.9.2.
Notice that everything after setting up the stringstream looks just like reading from a file. We even still use eof() even though there isn’t really a file that we are reading from - when working with a stringstream, eof() means β€œend of the stringstream”.

Checkpoint 11.9.1.

Construct a block of code that uses a string stream to break "April 22 2025" into the string "April" and the integers 25 and 2025.
You have attempted of activities on this page.