Show Lecture.Stringstreams as a slide show.
CS253 Stringstreams
Streams
- We’re all familiar with cin, cout, and cerr,
which are attached to the standard input, output, and error streams.
- Think of 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.
- Similarly,
ifstream in("foobar")
connects the input stream
in
to the file foobar
.
- Your program deals with
in
, which actually gets data from
the file foobar
.
Backing Store
- For both cases, the C++ iostream object has a backing store.
It’s the thing (standard error, the file
foobar
) that really
contains the data.
- The iostream object is just an interface between you
and the backing store.
Stringstreams
ostringstream 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
Convert 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
Let’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 🐠
Like 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?
Full power!
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