CS253: Software Development with C++

Spring 2023

Stringstreams

Show Lecture.Stringstreams as a slide show.

CS253 Stringstreams

Inclusion

To use stringstream objects, you need to:

    
#include <sstream>

Streams

Backing Store

Stringstreams

ostringstream example

ostringstream oss;
int n = 8675309;
oss << "Jenny, I got your number: " << n;
// Extract everything “printed” to the ostringstream.
string s = oss.str();
cout << s << '\n';
Jenny, I got your number: 8675309

Sure, an experienced C++ programmer would use to_string(), but that’s not the point:

int n = 8675309;
string s = "Jenny, I got your number: " + to_string(n);
cout << s << '\n';
Jenny, I got your number: 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