Show Lecture.Stringstreams as a slide show.
cin
, cout
, and cerr
,
which are attached to the standard input, output, and error streams.
cout
as being connected to the standard output stream.
Your program deals with the cout
object, which send the data
on to the standard output stream.
ifstream in("foobar")
connects the input stream
in
to the file foobar
.
in
, which actually gets data from
the file foobar
.
iostream
object has a backing store.
It’s the thing (standard error, the file foobar
) that really
contains the data.
iostream
object is just an interface between you
and the backing store.
stringstream
is an iostream
object that uses a
std::string
as a backing store.
ostringstream
writes to a std::string
.
istringstream
reads from a std::string
.
istringstream
or ostringstream
using <<
and >>
, just like any other iostream
object.
ostringstream
exampleostringstream oss; int n = 8675309; oss << "n is " << n << ", yes it is!"; // Extract everything that was “printed” to the ostringstream. string s = oss.str(); cout << s << '\n';
n is 8675309, yes it is!
Sure, an experienced C++ programmer would use to_string
,
but that’s not the point:
int n = 8675309; string s = to_string(n); cout << n << " becomes " << s << '\n';
8675309 becomes 8675309
istringstream
exampleConvert a std::string
to a double
:
string s = "+123.4560"; istringstream iss(s); // Initialize with the string double d; if (iss >> d) // Extract a double from the stream cout << s << " becomes " << d << '\n'; else cerr << "Error: can’t convert " << s << "\n";
+123.4560 becomes 123.456
istringstream
exampleLet’s watch it fail:
string s = "🐠"; istringstream iss(s); // Initialize with the string double d; if (iss >> d) // Try to get a double from the stream cout << s << " becomes " << d << '\n'; else cerr << "Error: can’t convert " << s << "\n";
Error: can’t convert 🐠
istringstream
exampleLike any stream, it reads only as much as it can:
istringstream iss("123🐠🍕🏥 🐕"); int n; string next; if (iss >> n >> next) cout << "n=" << n << " next=\"" << next << "\"\n"; else cerr << "Error: reading failed.\n";
n=123 next="🐠🍕🏥"
Why didn’t it read the dog?
Of course, you can use the full capabilities of formatting:
// Convert an int to a hex string: ostringstream oss; oss << "A brief story about overeating: " << hex << 14627408937814515373ULL << '\n'; cout << oss.str();
A brief story about overeating: cafefeedfacedead