String Streams (stringstream) in C++
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.
Build strings with ostringstream
std::ostringstream out; out << "x=" << x; then out.str() returns the assembled std::string.
Parse strings with istringstream
std::istringstream in(line); int a, b; then in >> a >> b; pulls numbers out of text, whitespace-delimited.
Check success
Extraction returns the stream, which converts to false on failure — if (in >> x) guards every parse.
Reset to reuse
A used stream holds state and old content: call ss.clear() plus ss.str("") before refilling it.
#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;}Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in C++ yourself — building beats watching.