CKTIS / C++
std::ostringstream — building text with a stream
std::ostringstream, declared in <sstream>, formats values into text stored in memory. It uses operator << like an output stream, while str() retrieves the result as a std::string.
Version: C++23; repository compiler flag, production runtime not attested
Syntax
#include <sstream>
std::ostringstream out;
out << value;
std::string text = out.str();std::ostringstream is an alias for std::basic_ostringstream<char>, declared in <sstream>. It is an output stream that writes to an internal string buffer rather than directly to a terminal or file. Use it to assemble messages from strings and numbers. std::istringstream reads from text, whereas std::stringstream supports both directions.
Insert values using <<. Manipulators such as std::fixed and std::setprecision(2) control formatting; together they request two digits after the decimal separator. Numeric formatting depends on the stream's locale. The example explicitly installs std::locale::classic() to obtain a decimal point.
Calling out.str() on a named stream returns a copy of the accumulated text as a std::string; it does not empty the buffer. To reuse the stream, replace its contents with out.str(std::string{});. Separately, out.clear(); resets error flags, not the text. Neither operation restores default formatting settings.
The example uses interfaces available in C++23. The supplied document is an evolving working draft and may also contain later additions. The repository compiler flag does not attest to the production runtime environment.
Examples
#include <iomanip>
#include <iostream>
#include <locale>
#include <sstream>
#include <string>
int main() {
std::ostringstream out;
out.imbue(std::locale::classic());
out << "items=" << 3 << "; price="
<< std::fixed << std::setprecision(2) << 12.5;
const std::string text = out.str();
std::cout << text << '\n';
}
Result
items=3; price=12.50
The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.