std::stringstream provides an in-memory stream for composing text with operator<< and parsing text with operator>>. It avoids the type-mismatch hazards of printf-style formatting and lets conversions report failure. section 4.3 section 5.7
The practical mistake is treating it as the best answer to every formatting problem. It is clean for ordinary values, but padding, alignment, and other detailed formatting can become more awkward than the original code. section 4.3
Use it when the stream operation makes the code safer or clearer:
- Compose a message from strings and numeric values without manually matching format specifiers to argument types. section 4.3
- Parse text into a numeric value, then test is.fail() so invalid input is handled instead of silently becoming zero. section 5.7
- Prefer std::stoi or std::from_chars when modern C++ provides a clearer or more efficient conversion path. section 5.7
Checked age conversion
Read the input into a std::istringstream, extract an int, and reject the value when is.fail() is true. This turns malformed text into an explicit invalid-input path rather than relying on atoi's indistinguishable zero result. section 5.7
Listing 4.6 Using stringstream for fine-grained formatting functionality
struct Student {
std::string name;
int age;
double gpa;
Student(const std::string& n, int a, double g) : name(n), age(a), gpa(g) {}
};
int main() {
Student dinah("Dinah", 26, 3.3);
std::stringstream str;
str << dinah.gpa;
std::string gpa_str(str.str());
str.str("");
str << dinah.name << " is a student aged " << dinah.age << " carrying a
gpa of "
<< gpa_str << std::setw(4 - gpa_str.size()) << std::setfill('0') << ""; #1
std::cout << str.str() << '\n';
return 0;
}
Compare the stringstream version of student-message formatting, including numeric conversion and GPA padding, with simpler and newer formatting approaches. section 4.3
