A string stream reads from and writes to a std::string#include <string>. It is available from the sstream header. There are three different kinds of string streams:

  • std::ostringstream#include <sstream> writes to a string.
  • std::istringstream#include <sstream> reads from a string.
  • std::stringstream#include <sstream> does both.

std::ostringstream#include <sstream> builds a string with <<, and str() returns the result as std::string#include <string>:

#include <sstream>

std::ostringstream#include <sstream> ss;
ss << "x = " << 42 << ", y = " << 3.5;
ss.str();  // "x = 42, y = 3.5"

std::istringstream#include <sstream> parses values from a string with >>:

std::istringstream#include <sstream> ss("the quick brown fox");
std::string#include <string> word;
while (ss >> word) {
  std::cout#include <iostream> << word << "\n";
}

A string stream can be reused by emptying its string with str("") and clearing its state with clear(), which resets flags such as end of input:

ss.str("");
ss.clear();

Note

From C++11 onwards, std::to_string#include <string>(), std::stoi#include <string>() and std::stod#include <string>() convert between numbers and strings more directly than a string stream.

References