Lesson 198 +10 XP

Stream Classes for Strings

Stream Classes for Strings

A stringstream is a stream that reads from and writes to a string in memory. You get all the stream power with no file or keyboard involved - perfect for formatting text and parsing data.

The three classes

  • stringstream - reads and writes a string.
  • istringstream - reads from a string (input).
  • ostringstream - writes to a string (output).

All three live in the <sstream> header.

Building a formatted string

Write into an ostringstream with << just like cout, then grab the finished text:

#include <sstream>
using namespace std;

ostringstream out;
out << "Score: " << 42 << " and pi is " << 3.14159;

string result = out.str();

The .str() method returns the whole string that the stream has built so far. Numbers come out converted to their text form automatically.

Parsing a string into variables

Read from an istringstream with >> to pull values back out:

string data = "Alice 25 3.5";
istringstream in(data);

string name;
int age;
double gpa;

in >> name >> age >> gpa;

Whitespace splits the string into tokens, and each >> hands the next token to a variable, converting it to the right type.

When to reach for stringstreams

  • Building a complex output line without juggling many + concatenations.
  • Converting numbers to strings (and back) with one easy step.
  • Parsing line-based or space-separated input files.

TL;DR

  • stringstream, istringstream, ostringstream live in <sstream>.
  • ostringstream builds a string with <<; read it with .str().
  • istringstream parses a string with >> into variables.
  • Whitespace splits tokens during extraction.
  • Great for formatting output and parsing text data.