You use a stringstream in C++ when a task mixes text and values. Common examples are building a line of output from several pieces, turning text into numbers, and reading structured text such as a line of data. Its main advantage is that it uses the same << and >> operators as std::cout and std::cin, so formatting and parsing code looks like ordinary input and output code.
Building formatted text
#include <iostream>
#include <sstream>
#include <string>
std::string make_label(int id, double score) {
std::ostringstream out;
out << "Player " << id << ": " << score << " points";
return out.str();
}
int main() {
std::cout << make_label(7, 93.5) << '\n'; // Player 7: 93.5 points
}
Writing the pieces into one stream keeps the code close to the output you want. The same job with + needs a conversion for each number, and you have less say in how each number looks.
Why not just use std::to_string?
std::to_string is short, but it formats a double with six decimal places. std::to_string(93.5) gives 93.500000, while a stream prints 93.5 by default. When you need a specific format, streams also work with manipulators such as std::setprecision, from <iomanip>.
Parsing text with mixed types
#include <iostream>
#include <sstream>
#include <string>
int main() {
std::istringstream in("Ada 36 4.5");
std::string name;
int age = 0;
double rating = 0.0;
in >> name >> age >> rating;
std::cout << name << " is " << age << ", rating " << rating << '\n';
}
The program prints Ada is 36, rating 4.5. One chain of >> reads three values of three different types, and the stream skips the spaces between them. Doing the same by hand with find and substr takes more code and more care.
Converting text to numbers
A stream reports a bad conversion through its state, so check the result of >> before you use the value. std::stoi reports the same problem by throwing std::invalid_argument. Both accept a partial value such as 12abc, so check the rest of the text when the whole text must be a number.
When a simpler option is better
- To turn one number into text,
std::to_stringis usually the shortest route. - To join a few strings,
+reads more clearly. - Stringstreams often cost more than plain string operations, so in performance-sensitive loops, measure before you choose one.
Summary
A stringstream earns its place when you need formatting or parsing that mixes text and values. For a single conversion or a simple join, a simpler tool is usually clearer.