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
.
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.
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:
.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:
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β.
"April 22 2025"
into the string "April"
and the integers 25
and 2025
.