stringstream

stringstream in C++

stringstream in C++ explained: how the <sstream> classes read and write text in memory, convert strings and numbers, split text, and avoid common mistakes.

On this page
  1. The three stringstream classes
  2. Building text with ostringstream
  3. Reading values with istringstream
  4. Converting between strings and numbers
  5. Splitting text into fields
  6. Reusing a stringstream
  7. Common mistakes
  8. When another tool is simpler
  9. Key points

A stringstream is a C++ object that reads and writes text in memory. You send values into it with <<, the same operator you use with std::cout, and you take values out of it with >>, the same operator you use with std::cin. It is declared in the <sstream> header, and it is useful for building text, parsing text, and converting between strings and numbers.

The three stringstream classes

The <sstream> header provides 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. It is the most flexible, but the one-direction classes make your intent clearer.

Include the header along with <string>, which provides std::string:

#include <sstream>
#include <string>

Building text with ostringstream

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

int main() {
    std::ostringstream out;
    int count = 3;
    double price = 4.5;

    out << "Total: " << count << " items at " << price;

    std::string text = out.str();
    std::cout << text << '\n';  // Total: 3 items at 4.5
}

Each << adds to the text inside the stream, the same way it would print to the screen. Nothing is shown until you take the text out with str(), which returns a copy of it as a std::string, and send it somewhere such as std::cout.

Reading values with istringstream

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

int main() {
    std::istringstream in("12 apples 7 pears");

    int number = 0;
    std::string word;
    while (in >> number >> word) {
        std::cout << number << " -> " << word << '\n';
    }
}

The output is:

12 -> apples
7 -> pears

The >> operator skips spaces and newlines before each value and stops at the next whitespace. That is why word holds apples and not 12 apples. The loop ends when a read fails, which happens when the input runs out or when the next text does not match the type being read.

Converting between strings and numbers

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

int main() {
    std::string text = "128";
    std::istringstream in(text);

    int value = 0;
    if (in >> value) {
        std::cout << value + 1 << '\n';  // 129
    } else {
        std::cout << "Not a number\n";
    }

    std::ostringstream out;
    out << 255;
    std::string digits = out.str();
    std::cout << digits << '\n';  // 255
}

The if checks whether the read worked. A failed read sets an error flag on the stream, and the if sees it.

Partial input needs care. The text 12abc reads as 12, and the stream stops at the letter, so the read still succeeds. If the whole text must be a number, check what is left in the stream, or validate the text before you read it.

std::stoi is the other common choice. It throws std::invalid_argument when the text has no number at all. Like the stream, it accepts a partial value such as 12abc.

Splitting text into fields

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

int main() {
    std::string row = "Ada,Lovelace,1815";
    std::istringstream fields(row);

    std::string part;
    while (std::getline(fields, part, ',')) {
        std::cout << part << '\n';
    }
}

std::getline reads up to a delimiter, here a comma, and discards the delimiter. Splitting on a delimiter is one of the most common jobs for a string stream, and the same loop works on a line read from a file or from std::cin.

Reusing a stringstream

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

int main() {
    std::istringstream in("1 2");
    int n = 0;
    while (in >> n) {
        std::cout << n << '\n';  // prints 1, then 2
    }

    in.clear();     // reset the error and end-of-input flags
    in.str("5 6");  // replace the text
    while (in >> n) {
        std::cout << n << '\n';  // prints 5, then 6
    }
}

Once a read reaches the end or fails, the stream keeps that state. str() replaces the text but does not clear the flags, so call clear() as well. For an ostringstream, call out.str("") to empty it before you reuse it.

Common mistakes

  • Forgetting #include <sstream>. The compiler reports that ostringstream, istringstream or stringstream is not declared.
  • Forgetting str(). Writing into an ostringstream fills the buffer but prints nothing. Take the text out first.
  • Reusing a stream without clear(). After a failed read, later reads keep failing until you clear the flags.
  • Using >> to read a whole line. >> stops at the first space. Use std::getline for lines.
  • Trusting a partial read. 12abc reads as 12, and the read succeeds.

When another tool is simpler

A stringstream is not always the best choice.

  • To turn one number into text, std::to_string is shorter and needs no stream. It formats a double with six decimal places, so std::to_string(4.5) gives 4.500000.
  • To join a few strings, + or += on std::string is usually clearer.
  • For simple searches and cuts, the std::string member functions, such as find and substr, are often enough. Those are the everyday part of c string methods.
  • Stringstreams often cost more than plain string operations. In performance-sensitive loops, measure before you choose one.

Key points

  • A stringstream reads and writes text in memory with << and >>.
  • Use ostringstream to build text and istringstream to parse it.
  • str() returns the text. clear() resets the error flags so a stream can be reused.
  • A read stops at the first thing it cannot parse, so check the result.

Keep exploring

Guides from other topics

All topics →

Class Constructors in C++

Learn C++ class constructors with compilable examples: default and parameterized forms, member initializer lists, explicit, and initialization order.

Constructors 6 min read

Friend Functions in C++

Learn what a friend function is in C++, how the friend keyword lets a non-member function reach private members, and when to use one, with code examples.