Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

std::ostream and std::basic_ostream — output streams

std::basic_ostream is an output-stream template, and std::ostream is its alias for char. They support formatting values with operator<< and writing characters to an associated stream buffer.

Version: C++23; repository compiler flag, production runtime not attested

Syntax

#include <ostream>
std::basic_ostream<CharT, Traits>
std::ostream // std::basic_ostream<char, std::char_traits<char>>
std::ostream& write_value(std::ostream& out, int value);

std::basic_ostream<CharT, Traits> from <ostream> provides an interface for output to a stream buffer. CharT selects the character type, while Traits supplies character operations; its default is std::char_traits<CharT>. std::ostream is exactly an alias for std::basic_ostream<char>, not a separate template or an output object.

operator<< formats values such as numbers. Insertion operations return a reference to the stream, allowing calls to be chained. put(c) writes one character, while write(s, n) writes n characters without formatting unless output fails. flush() requests synchronization of the associated buffer; it does not guarantee durable storage on disk.

Accept std::ostream& so a function can use the supplied stream without copying it. In the example, write_value receives std::cout and returns the same stream, after which put('\n') appends a newline character. A bare \n does not request a flush; the example calls flush() explicitly.

Output errors are reported through stream state, including failbit or badbit; the exception mask can cause an exception to be thrown. Do not assume that the absence of an exception means success: check the state, as the example's final condition does. This entry targets C++23; the compilation standard does not attest a production runtime. The sources present an evolving standard draft.

Examples

#include <iostream>
#include <locale>
#include <ostream>

std::ostream& write_value(std::ostream& out, int value) {
    return out << "value=" << value;
}

int main() {
    std::cout.imbue(std::locale::classic());
    write_value(std::cout, 42).put('\n');
    std::cout.flush();
    return std::cout ? 0 : 1;
}

Result

value=42

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources