C++ stringstream formatting and parsing code

C++ stringstream for Formatting and Parsing

A C++ stringstream lets you treat a string like a stream. You can insert formatted values with <<, retrieve the complete result with str(), and extract typed values with >>. This makes it useful for both building text and converting text into integers, floating-point values, and other supported types.

Include <sstream> before constructing std::stringstream. The stream maintains text plus state flags, so reliable code checks extraction results and resets both parts before reuse.

Create a C++ stringstream with <sstream>

The default constructor creates an empty stream that supports both input and output. You can write into it immediately. To start with existing text, pass a string to the constructor.

Example: #include <sstream> int main() { std::stringstream stream; stream << “ready”; }

This example compiles because the stream is an ordinary local object. Unlike std::cout, it stores inserted output in memory rather than displaying it. You can later retrieve that stored text or read it back through the same stream.

Build a formatted string with insertion and str()

Use the insertion operator to append values in sequence. The stream applies formatting rules as it processes each value, so you can combine labels, numbers, and manipulators without manually converting each item.

Example: #include <iomanip> #include <iostream> #include <sstream> int main() { std::stringstream stream; stream << “Order ” << 17 << “: $” << std::fixed << std::setprecision(2) << 8.5; std::cout << stream.str() << ‘\n’; }

str() returns the stream’s current contents as a std::string. In this example, the output is Order 17: $8.50. Formatting settings such as std::fixed remain active for later insertions until you change them or reset the stream.

Parse typed values with extraction and detect leftover input

Construct a stream from text, then use extraction to convert values. Each extraction advances through the input and assigns the converted result to a variable. If the text cannot represent the requested type, the stream sets its failure state.

Example: #include <iostream> #include <sstream> #include <string> int main() { std::stringstream input(“42 3.5 leftover”); int quantity; double price; if (!(input >> quantity >> price)) return 1; input >> std::ws; if (input.peek() != std::char_traits<char>::eof()) { std::cout << “Unexpected input\n”; return 1; } std::cout << quantity << ‘ ‘ << price << ‘\n’; }

The first two extractions succeed, but leftover remains in the buffer. The call to std::ws consumes trailing whitespace, and peek() checks whether any non-whitespace character remains. This distinction matters when you want to reject input such as 42 3.5abc instead of silently accepting only its valid prefix.

Check fail state and clear flags and stored text before reuse

Test an extraction directly with if (stream >> value), or inspect stream.fail() afterward. The fail state indicates that a formatted operation could not produce the requested value. Once failbit is set, later input and output operations generally do nothing until you call clear(). eof() reports that reading reached the end, while good() is true only when no state flags are set.

Calling clear() resets state flags, but it does not remove stored characters. Calling str(“”) replaces the buffer with an empty string, but it does not clear a previous failure. Use both when you want a clean stream.

Example: #include <sstream> #include <string> int main() { std::stringstream stream(“bad”); int value{}; stream >> value; if (stream.fail()) { stream.clear(); stream.str(“”); } stream << “retry ” << 7; std::string result = stream.str(); return result == “retry 7” ? 0 : 1; }

Here, extraction fails because bad is not an integer. The paired reset removes the failure flag and the old text, allowing the stream to build a new result. To reuse it for new input instead, use stream.clear() followed by stream.str(“18 blue”), then extract from the replacement text.