Learn C++
#include "ioformatting/stringstream.hpp"

String Streams (stringstream) in C++

//concept

A std::stringstream from <sstream> is a stream that reads and writes strings instead of the console — the same << and >> operators, but in memory. It converts between text and values (parse "42" into int, build "score=42" from parts) using the exact conversions cout/cin would apply.

Two everyday patterns: ostringstream to assemble formatted strings without manual concatenation, and istringstream to split a line into tokens with >> in a loop. Always check the stream's state after parsing — a failed extraction sets failbit and leaves the target untouched.

//how it works
1

Build strings with ostringstream

std::ostringstream out; out << "x=" << x; then out.str() returns the assembled std::string.

2

Parse strings with istringstream

std::istringstream in(line); int a, b; then in >> a >> b; pulls numbers out of text, whitespace-delimited.

3

Check success

Extraction returns the stream, which converts to false on failure — if (in >> x) guards every parse.

4

Reset to reuse

A used stream holds state and old content: call ss.clear() plus ss.str("") before refilling it.

//example
#include <iostream>
#include <sstream>
#include <string>
 
int main() {
std::istringstream in("10 20 30");
int a = 0, b = 0, c = 0;
in >> a >> b >> c;
std::cout << (a + b + c) << std::endl;
return 0;
}
Output
60
1The istringstream wraps the literal text as if it had been typed at the console.
2Three >> extractions parse 10, 20, 30 into the ints, splitting on spaces exactly like cin would.
3The sum 60 prints, proving text became genuine numbers, not concatenated characters.
//use cases
Splitting a getline result into fields without manual find/substr loops
Converting numbers to strings and back with full formatting control
Validating user input by parsing and checking the stream state
Building log and error messages from mixed values in one expression

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Re-implement each visualized algorithm in C++ yourself — building beats watching.