liveBook · Manning

Std::stringstream

As explained in 100 C++ Mistakes and How to Avoid Them

std::stringstream is a C++ standard-library stream class that supports formatted input and output through an in-memory character sequence.

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

How 100 C++ Mistakes and How to Avoid Them covers it

How deep it goes
Shows output composition and conversion checks, but identifies detailed padding and alignment as awkward.
Examples
Demonstrates student-message formatting with GPA padding and checked age parsing from user-entered text.
What you can do after
Apply it via stream operators to compose text and detect failed numeric conversions.
How it connects
Connects stringstream with formatted I/O, stream operators, input validation, std::istringstream, std::stoi, std::from_chars, and std::format.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of 100 C++ Mistakes and How to Avoid Them. The section links point to the parts of the book it draws on.