The <sstream> header gives C++ string streams. A string stream is a stream object that moves text in and out of a std::string held in memory, instead of the keyboard, the screen, or a file. You use the same << and >> operators you already know from std::cout and std::cin, so the code looks familiar.
The three classes
The header defines three classes:
std::ostringstreamwrites into a string. Use it to build text from values.std::istringstreamreads from a string. Use it to pull values out of text.std::stringstreamdoes both.
Each one has a str() member function that returns a copy of the text the stream holds.
A short example
#include <iostream>
#include <sstream>
#include <string>
int main() {
std::ostringstream out;
out << "Score: " << 42;
std::cout << out.str() << '\n'; // Score: 42
std::istringstream in("7 8 9");
int a = 0;
int b = 0;
int c = 0;
in >> a >> b >> c;
std::cout << a + b + c << '\n'; // 24
}
The first half builds the text Score: 42 and prints it. The second half reads three numbers from the string 7 8 9 and adds them up to get 24.
Why the stream style helps
String streams use the same formatting rules as console and file input and output. Once you know how << writes a number to std::cout, you already know how it writes that number into a string. You also learn one set of rules for parsing text, whether the text came from a file or from memory.
Which headers to include
<sstream>for the string stream classes.<string>forstd::string.<iostream>only if you print withstd::cout, because<sstream>does not provide it.
Common mistakes
- Leaving out
#include <sstream>. The compiler reports thatostringstreamoristringstreamis not declared. - Expecting output to appear by itself. Writing into an
ostringstreamonly fills the buffer. Callstr()to get the text, then print it. - Passing a stream by value. Streams cannot be copied, so take them by reference, such as
std::istringstream& in.
Summary
The <sstream> header lets you treat a string as a stream. Use std::ostringstream to build text, std::istringstream to read it, and std::stringstream when you need both.