CS253: Software Development with C++

Fall 2020

Stringstreams

Show Lecture.Stringstreams as a slide show.

CS253 Stringstreams

Streams

Backing Store

Stringstreams

ostringstream example

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

istringstream example

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

istringstream example

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 🐠

istringstream example

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