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::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. 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 thatostringstream,istringstreamorstringstreamis not declared. - Forgetting
str(). Writing into anostringstreamfills 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. Usestd::getlinefor lines. - Trusting a partial read.
12abcreads as12, 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_stringis shorter and needs no stream. It formats adoublewith six decimal places, sostd::to_string(4.5)gives4.500000. - To join a few strings,
+or+=onstd::stringis usually clearer. - For simple searches and cuts, the
std::stringmember functions, such asfindandsubstr, 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
stringstreamreads and writes text in memory with<<and>>. - Use
ostringstreamto build text andistringstreamto 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.