stringstream

What Does <sstream> Do in C++?

What does <sstream> do in C++? It provides classes that read and write text in memory, using the same << and >> operators as cin and cout, with examples.

On this page
  1. The three classes
  2. A short example
  3. Why the stream style helps
  4. Which headers to include
  5. Common mistakes
  6. Summary

The <sstream> header gives C++ string streams. A string stream is a stream object that moves text in and out of a std::string held in memory, instead of the keyboard, the screen, or a file. You use the same << and >> operators you already know from std::cout and std::cin, so the code looks familiar.

The three classes

The header defines three classes:

  • std::ostringstream writes into a string. Use it to build text from values.
  • std::istringstream reads from a string. Use it to pull values out of text.
  • std::stringstream does both.

Each one has a str() member function that returns a copy of the text the stream holds.

A short example

#include <iostream>
#include <sstream>
#include <string>

int main() {
    std::ostringstream out;
    out << "Score: " << 42;
    std::cout << out.str() << '\n';  // Score: 42

    std::istringstream in("7 8 9");
    int a = 0;
    int b = 0;
    int c = 0;
    in >> a >> b >> c;
    std::cout << a + b + c << '\n';  // 24
}

The first half builds the text Score: 42 and prints it. The second half reads three numbers from the string 7 8 9 and adds them up to get 24.

Why the stream style helps

String streams use the same formatting rules as console and file input and output. Once you know how << writes a number to std::cout, you already know how it writes that number into a string. You also learn one set of rules for parsing text, whether the text came from a file or from memory.

Which headers to include

  • <sstream> for the string stream classes.
  • <string> for std::string.
  • <iostream> only if you print with std::cout, because <sstream> does not provide it.

Common mistakes

  • Leaving out #include <sstream>. The compiler reports that ostringstream or istringstream is not declared.
  • Expecting output to appear by itself. Writing into an ostringstream only fills the buffer. Call str() to get the text, then print it.
  • Passing a stream by value. Streams cannot be copied, so take them by reference, such as std::istringstream& in.

Summary

The <sstream> header lets you treat a string as a stream. Use std::ostringstream to build text, std::istringstream to read it, and std::stringstream when you need both.

The complete guide to stringstream

stringstream in C++
Read the guide

Keep exploring

Guides from other topics

All topics →

std::array in C++

A complete guide to std::array in C++: declaring, initializing, reading elements, looping, passing to functions, and how it compares to C-style arrays.

std::array 5 min read