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.
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.
istringstream
String streams support all the normal iostream capabilities. There are only two additional things you need.
istringstream
.str()
.#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.
ostringstream
Simlarly, there are only a couple of things you need to know to use output string streams.
ostringstream
.str()
.#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.