Skip to content
Tutorials Center
My learning

Topics

Lesson 125 of 171 ยท Input/Output and Files

String Streams

Use C++ string streams - parse text with istringstream, build strings with ostringstream, split strings with getline, reuse streams safely, and when std::format is better.

A string stream is a stream whose "device" is a std::string in memory. Reading from an std::istringstream works exactly like reading from std::cin or a file, except that the characters come from a string you supply. Writing to an std::ostringstream works like std::cout, except that the output collects in a string you can take afterwards. Everything you learned in I/O Streams in Depth, >>, getline, state flags and manipulators, applies unchanged.

That makes string streams the standard tool for two jobs: parsing a line of text into values, and building a string from mixed pieces. This lesson covers both, plus splitting strings on a delimiter, validating conversions, reusing a stream correctly, and an honest comparison with the modern alternatives std::format, std::from_chars and ranges.

All three classes live in <sstream>:

Class Direction Typical job
std::istringstream read from a string parsing
std::ostringstream write into a string building text
std::stringstream both conversions in both directions, or when you need both at once

Prefer the one-directional classes: they say what you mean and can't be used the wrong way by accident.

Parsing with istringstream

Create an std::istringstream from a string and read from it with >>. Each extraction skips whitespace, converts the next token to the target type, and sets failbit if the text doesn't fit. Here's a parser for simple drawing commands:

C++ Parsing values out of a string

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

In the second case, w reads 4 and then h meets wide. That extraction fails, stores 0 in h, and puts the stream into the fail state.

Line by line, then token by token

The most useful pattern combines two levels: read whole lines from a file or std::cin with std::getline, then parse each line with its own std::istringstream. That keeps lines separate, which plain >> can't do (it treats newlines as ordinary whitespace), and one bad line can't derail the rest.

C++ A command interpreter, one line at a time

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

The check !words.eof() after the loop tells the two ways the number loop can end apart. If extraction stopped because the line ran out, eofbit is set. If it stopped at junk like x, the stream failed before reaching the end, so eofbit is still clear.

Splitting a string on a delimiter

std::getline takes an optional third argument: the delimiter character. With an std::istringstream, that turns it into a simple split function. Unlike >>, it keeps spaces inside fields and returns empty fields between two delimiters, which is what you want for comma-separated data.

C++ Splitting with getline and a delimiter

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Look closely at the third result: "a,b," gives only ["a", "b"]. After reading b, the stream is exactly at the end, so the next getline fails instead of returning an empty string. If trailing empty fields matter (they do in strict CSV), split with find and substr, or with std::views::split as shown at the end of this lesson. Real CSV also has quoted fields containing commas, which no simple split handles; use a CSV library for that.

Strict conversions: did the whole string match?

>> stops at the first character that doesn't fit and calls that a success. Reading an int from "42abc" gives 42 without complaint. When you need to know that the entire string was a number, check that nothing but whitespace is left afterwards:

C++ Validating that the whole string was consumed

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

std::ws is an input manipulator that eats whitespace. After it, eof() is only true if the string had nothing else left. "3.5" fails as an int because .5 remains, but succeeds as a double.

This works for any type with an operator>>, which is its main advantage. For plain numbers, though, std::from_chars (from Converting Between Strings and Numbers) is the better tool: it's many times faster, never allocates, doesn't depend on the locale, and reports exactly where parsing stopped.

Building strings with ostringstream

An std::ostringstream collects everything you write into it. Call str() to get a copy of the result as a std::string. Before std::format existed, this was the standard way to build a string from numbers and text, and it's still useful when you already have stream-based code, such as an operator<< for your own type, which you saw in Operator Overloading.

C++ ostringstream, str() and reusing a stream

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

The last part prints firstsecond. The name clear() misleads many people: it clears the error flags, not the contents. To reuse a string stream, call str("") (to empty it) and clear() (in case a previous operation failed). Often it's simpler and just as fast to create a new stream inside the loop.

Two more details:

  • str() returns a copy of the buffer. In C++20 you can call view() to get a std::string_view without copying, or std::move(stream).str() to move the string out when you're done with the stream.
  • str(s) on an std::istringstream replaces the text to parse, which lets one stream parse many lines; call clear() as well, because the previous line probably ended in eof.

Modern alternatives

String streams are flexible, but they're not the fastest or most concise tool for every job. Since C++20 and C++23 you have better options for common tasks:

Task String stream Modern alternative
Build a formatted string std::ostringstream + << + manipulators std::format("{:>8.2f}", x)
Number to string oss << n; oss.str() std::format("{}", n), std::to_string(n), std::to_chars
String to number iss >> n std::from_chars (fast, no locale, no exceptions)
Split on a delimiter std::getline(iss, part, ',') std::views::split(text, ',')
Parse mixed whitespace-separated values iss >> a >> b >> c still a good use of string streams

std::format, covered in Formatting with std::format and std::print, is usually shorter, it's type-safe, and it doesn't leave sticky formatting state behind. Here are the same tasks written both ways:

C++ String streams versus format, from_chars and views::split

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

The split view produces [a][b][], including the trailing empty field that the getline version dropped, and each part is a view into the original string rather than a copy.

So when should you still reach for a string stream? When you parse whitespace-separated values of different types in one go (in >> name >> age >> score), when you need the std::istream/std::ostream interface for an existing function or operator<<, and when you work in code that already uses streams. For new formatting code, prefer std::format; for number conversion in hot loops, prefer std::from_chars and std::to_chars.

C++23 also adds span streams in <spanstream>: std::ispanstream and std::ospanstream read from and write to an existing character buffer (a std::span<char>) instead of an owned std::string, which avoids allocation entirely when you already have the text in memory.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does this print? std::istringstream in("7 8 nine 10"); int a, b, c = -1; in >> a >> b >> c; std::println("{} {}", c, in.fail());

    a and b read 7 and 8. Extracting "nine" as an int fails, which stores 0 in c and sets failbit.
  2. 2. How many parts does splitting "x,,y" with while (std::getline(in, part, ',')) produce?

    getline with a delimiter returns the empty text between two adjacent commas. Only a trailing empty field after the final delimiter is lost.
  3. 3. std::ostringstream s; s << "ab"; s.clear(); s << "cd"; What is s.str()?

    clear() only resets the error flags. To empty the stream, call s.str("").
  4. 4. Why parse each line with its own istringstream instead of reading everything with std::cin >> directly?

    Reading lines first preserves line structure, and a failure in one line's stream doesn't put std::cin into the fail state.
  5. 5. Using parse_exact from this lesson, what does parse_exact<int>("42abc") return?

    The extraction succeeds with 42, but after skipping whitespace the stream isn't at its end, so the function rejects the input.

Summary

  • std::istringstream parses a string with >> and getline; std::ostringstream builds one with << and returns it with str().
  • Read lines with std::getline, then parse each line with its own istringstream; eof() afterwards shows whether the whole line was consumed.
  • std::getline(in, part, ',') splits on a delimiter and keeps empty fields, except a trailing one.
  • For strict conversions, check (in >> std::ws).eof() after reading; for numbers, std::from_chars is faster.
  • clear() resets error flags only; reuse a stream with str("") plus clear(), or create a new one.
  • Prefer std::format for building strings and std::views::split for splitting; string streams shine for mixed-type, whitespace-separated parsing and operator<< code.

Next: The Filesystem Library, where you'll work with paths, directories and file metadata.