§The Annotated C++ StandardC++ 标准注疏 中文
31.7.6

Output streams: basic_ostream

Output streams

How basic_ostream writes: the sentry flushes the tied stream before output and flushes per unitbuf afterwards; padding and width reset in formatted output; why numeric inserters set badbit on failure and why negative numbers print as unsigned under hex; the deleted character inserters; the special rules for print to an ostream; and put, write, flush and manipulators such as endl.

Key points

  • Every output first constructs a sentry: it flushes the tied stream; on destruction, if unitbuf is on (as it is for cerr by default), it flushes this stream, but not during stack unwinding.
  • Formatted output pads according to width() and fill(); width is reset to zero by the inserter after one use, while fill and flags stay in effect.
  • Numbers are generated by num_put. Under hex or oct, an int is first converted to an unsigned number of the same width, so cout << hex << -1 prints ffffffff. If the stream buffer will not accept the characters, badbit is set.
  • cout << u8"x", cout << L'x' and the like select deleted overloads and are compile errors since C++20; int8_t and uint8_t print as characters; a null const char* is UB.
  • std::print(os, ...) neither looks at nor resets the stream's width and flags; a format error throws format_error directly without changing the stream state. endl is a newline plus a flush; use '\n' for bulk output.

Width applies once#

C++width-once.cpp✓ well-formedgodbolt ↗
#include <iomanip>
#include <iostream>
#include <sstream>

int main() {
  std::ostringstream os;
  os << std::setw(6) << 1 << 2;            // width applies only to the first
  std::cout << '[' << os.str() << "]\n";   // [     12]
  std::cout << '[' << std::setw(5) << 'x' << "]["
            << std::left << std::setw(5) << "ab" << "]\n";
  // [    x][ab   ]
  std::cout << std::right << std::setfill('0') << std::internal
            << std::setw(7) << -42 << '\n';   // -000042
}

setw(6) pads only the 1, and the 2 that follows is output as usual; left and setfill, once set, stay in effect. To understand the difference, we need the common rules of formatted output.

The sentry: fixed steps before and after output [ostream.sentry]#

basic_ostream also has a nested class sentry (sentry), constructed at the start of every output function and destroyed at its end.

C++
class basic_ostream<charT, traits>::sentry {
  bool ok_;   // exposition only
public:
  explicit sentry(basic_ostream& os);
  ~sentry();
  explicit operator bool() const { return ok_; }
  sentry(const sentry&) = delete;
  sentry& operator=(const sentry&) = delete;
};

¶2 The constructor: if os.good() is true, it prepares for output, which includes calling os.tie()->flush() if os.tie() is non-null. A footnote notes that the flush may be skipped when it can be determined that no synchronization is needed. ¶3 After the preparation, ok_ equals os.good().

Unlike the input stream's sentry, when the stream is not in a good state the output sentry does not add failbit; it just makes ok_ false.

¶4 The destructor: if (os.flags() & ios_base::unitbuf) && !uncaught_exceptions() && os.good() is true, it calls os.rdbuf()->pubsync(). If that returns −1 or throws, badbit is set on the stream, but the exception is not propagated.

The unitbuf flag means flush after every output; cerr has it on by default, and that flush happens in the sentry's destructor. The !uncaught_exceptions() in the condition means that if the output function is exiting because of an exception (for example a user type's operator<< threw), the sentry is destroyed during stack unwinding and does not flush, to avoid raising a new error while one exception is being handled.

Formatted output [ostream.formatted.reqmts]#

The members of basic_ostream fall into two groups ([ostream.general]/3): formatted output functions, also called inserters, and unformatted output functions. Both write characters via actions equivalent to rdbuf()->sputc().

[ostream.general]/3 also specifies that they shall not call any virtual function of the stream buffer other than overflow(), xsputn() and sync(). So a custom output stream buffer works with every inserter as long as it implements these three well ([stream.buffers]).

¶1 A formatted output function first constructs a sentry and, if it is true, makes a best effort to generate the output:

  • If generation fails, it calls setstate(failbit), which may throw.
  • If an exception is thrown during output, badbit is set on the stream (this step itself does not cause ios_base::failure to be thrown); if exceptions() contains badbit, the exception is rethrown.
  • With or without an exception, the sentry is destroyed before leaving the function; without an exception, *this is returned.

[ostream.general]/4 adds a general rule: when a function called by an output function throws, unless otherwise specified, badbit is set; if exceptions() contains badbit the exception is rethrown immediately, otherwise processing continues as if the called function had returned a failure indication.

Padding (¶3)#

¶3 When a formatted output function determines padding, if the length of the character sequence is less than os.width(), enough copies of os.fill() are added to bring the length up to width(). If adjustfield is left, the fill characters go after; otherwise they go before.

This paragraph distinguishes only left from everything else. internal (padding between the sign or 0x prefix and the digits, like the -000042 above) is meaningful only for numbers and is implemented by num_put ([facet.num.put.virtuals]).

The common rules say nothing about resetting the width to zero. It is each inserter that calls width(0) in its own specification: the character and string inserters, quoted, and num_put::do_put used for numeric formatting. That is why setw affects only the next insertion, while fill and flags stay in effect.

Custom inserters and setw#

If a user-written operator<< is assembled from several insertions, setw applies only to the first. To make the width apply to the whole value, format it into a string in a temporary stream first, then insert it once:

C++money-inserter.cpp✓ well-formedgodbolt ↗
#include <iomanip>
#include <iostream>
#include <sstream>

struct Money { long cents; };

std::ostream& operator<<(std::ostream& os, Money m) {
  std::ostringstream tmp;                   // assemble in a temporary stream
  tmp << m.cents / 100 << '.'
      << std::setw(2) << std::setfill('0') << m.cents % 100;
  return os << tmp.str();                   // one insertion: width applies to the whole
}

int main() {
  std::cout << '[' << std::setw(8) << Money{1234} << "]\n";   // [   12.34]
}

Arithmetic inserters [ostream.inserters.arithmetic]#

C++hex-negative.cpp✓ well-formedgodbolt ↗
#include <iostream>

int main() {
  std::cout << std::hex << -1 << ' '
            << static_cast<short>(-1) << '\n';   // ffffffff ffff
}

¶1 The arithmetic inserters generate characters with the num_put of the stream's locale. For bool, long, unsigned long, long long, unsigned long long, double, long double and const void*, the effect is as if:

C++
bool failed = use_facet<num_put<charT, ostreambuf_iterator<charT, traits>>>(
  getloc()).put(*this, *this, fill(), val).failed();

Other types are converted first and then handed to num_put:

Type of val Value passed to num_put
short long(static_cast<unsigned short>(val)) if the base is oct or hex, otherwise long(val)
int long(static_cast<unsigned int>(val)) if the base is oct or hex, otherwise long(val)
unsigned short, unsigned int static_cast<unsigned long>(val)
float static_cast<double>(val)

So in hexadecimal and octal, int and short are first converted to unsigned numbers of the same width, and -1 prints as ffffffff or ffff, not -1.

¶2 The first argument is an ostreambuf_iterator, which bypasses ostream and writes the stream buffer directly. If failed is true, setstate(badbit) is called. It is badbit here, not the failbit of the common rules: failed() being true means some sputc returned eof(), i.e. the stream buffer will no longer accept characters, which is a problem at the I/O layer.

¶4 C++23 operator<<(const volatile void* p) is equivalent to operator<<(const_cast<const void*>(p)). Before C++23 there was no such overload: a volatile int* cannot convert to const void*, only to bool, so it printed 1:

C++volatile-pointer.cpp✓ well-formedgodbolt ↗
#include <iostream>

int main() {
  volatile int vi = 0;
  std::cout << &vi << '\n';   // prints an address since C++23; prints 1 with -std=c++20 in our tests
}

¶5 C++23 Extended floating-point types are converted to double or long double and then output; when wider than long double, this inserter is conditionally-supported.

Other inserters [ostream.inserters]#

¶1–¶6 The three operator<< overloads taking function pointers are not formatted output functions; they just call pf(*this). Manipulators like endl and hex work through them.

¶7–¶9 out << sb (where sb is a basic_streambuf*) behaves as an unformatted output function. If sb is null, badbit is set. Otherwise characters are taken from sb and inserted into *this until sb reaches end-of-file, an insertion fails, or an exception is thrown while getting a character from sb. If no characters were inserted, failbit is set; if an exception was thrown while getting a character, failbit is also set, and the exception is rethrown if exceptions() contains failbit.

out << in.rdbuf() is the idiomatic way to copy the entire remaining content of one stream to another:

C++copy-rdbuf.cpp✓ well-formedgodbolt ↗
#include <iostream>
#include <sstream>

int main() {
  std::istringstream in("line1\nline2\n");
  std::ostringstream out;
  out << in.rdbuf();
  std::cout << out.str().size() << '\n';   // 12

  std::istringstream empty("");
  std::ostringstream o2;
  o2 << empty.rdbuf();                     // no characters inserted
  std::cout << o2.fail() << '\n';          // 1: failbit
}

¶11 C++17 out << nullptr outputs an implementation-defined string; libc++ outputs nullptr in our tests.

Characters and strings [ostream.inserters.character]#

¶1 The single-character inserters are formatted output functions: if the character is a char and the stream's character type is not char, it is first widened with out.widen(c); then it is padded according to the width, inserted, and finally width(0) is called.

¶3–¶4 The inserters for const charT* and const char* first compute the length with traits::length(s) (with char_traits<char>::length(s) when a wide stream accepts a const char*), widen each character, and then likewise pad, insert and call width(0). The precondition is that s is not a null pointer:

C++null-cstring.cpp☠ undefined behavior
#include <iostream>

int main() {
  const char* p = nullptr;
  std::cout << p << '\n';    // UB: precondition violated; segfaults with libc++ in our tests
}

Deleted overloads#

C++deleted-inserters.cpp✗ ill-formed
#include <iostream>

int main() {
  std::cout << u8"text";   // error: selects a deleted overload
  std::cout << L'x';       // error: same
  std::cout << u"text";    // error: same
}

The inserters of char streams for wchar_t, char8_t, char16_t, char32_t and pointers to them, and the inserters of wchar_t streams for char8_t, char16_t, char32_t and pointers to them, are all declared = delete. The note in ¶5 explains the purpose: to prevent printing a character as an integer and a string as a pointer value.

Before C++20, std::cout << u'X' promoted the character to an integer and printed that, std::cout << u"text" printed the pointer value, and u8"text", whose type was const char[] at the time, printed normally. With the introduction of char8_t in C++20, all of these became ill-formed ([diff.cpp17.input.output]).

int8_t and uint8_t print as characters

C++int8-print.cpp✓ well-formedgodbolt ↗
#include <cstdint>
#include <iostream>

int main() {
  std::int8_t a = 65;
  std::uint8_t b = 66;
  std::cout << a << ' ' << +a << ' ' << b << '\n';   // A 65 B
}

They are usually aliases for signed char and unsigned char, and the selected inserter is equivalent to out << static_cast<char>(c). Unary + performs integral promotion first, yielding an int, which then prints as a number. The current draft moves the inserters for signed char, unsigned char and pointers to them to Annex D ([depr.ostream.inserters]); this is post-C++23 wording deprecated.

C++print-ostream.cpp✓ well-formedgodbolt ↗
#include <format>
#include <iomanip>
#include <iostream>
#include <ostream>
#include <sstream>

int main() {
  std::ostringstream os;
  os << std::setw(10) << std::hex;          // no effect on print
  std::print(os, "{}|{:x}", 255, 255);
  std::cout << '[' << os.str() << "]\n";    // [255|ff]
  std::cout << os.width() << '\n';          // 10: print did not reset width

  os.exceptions(std::ios_base::badbit);
  try {
    std::print(os, std::dynamic_format("{:d}"), "str");  // run-time format error
  } catch (const std::format_error&) {
    std::cout << "format_error, bad=" << os.bad() << '\n'; // bad=0
  }
}

The print and println in <ostream> accept only ostream&, i.e. char streams.

  • ¶1 print(os, fmt, args...): calls vprint_unicode if the ordinary literal encoding is UTF-8, otherwise vprint_nonunicode.
  • ¶2 println(os, fmt, args...) is equivalent to print(os, "{}\n", format(os.getloc(), fmt, args...)): it formats into a string first, then outputs it together with the newline. ¶3 println(os) outputs only a newline.

¶4 vprint_unicode(os, ...) and vprint_nonunicode(os, ...) behave as formatted output functions, with two exceptions:

  • ¶4.1 failure to generate output is reported as specified below;
  • ¶4.2 an exception thrown by vformat is propagated unchanged, regardless of os.exceptions(), and without setting badbit on os.

After constructing the sentry, the function first executes string out = vformat(os.getloc(), fmt, args);. ¶4.3 If it is vprint_unicode and os refers to a terminal capable of displaying Unicode only via a native Unicode API (how this is determined is implementation-defined), it flushes os and then writes out using the native API; if out contains invalid code units, UB; it then establishes an observable checkpoint. ¶4.4 Otherwise it inserts the characters of out into os. If writing to the terminal or inserting fails, it calls os.setstate(badbit). ¶5 recommends that implementations replace invalid code units with U+FFFD when transcoding.

Three conclusions follow:

  1. The stream's format state does not affect print. width, flags, fill and precision play no part; the format is determined entirely by the format string. Only the locale participates, and only for replacement fields with the L option.
  2. print does not reset width to zero. The specification never calls width(0), so a previously set setw is left for the next <<.
  3. Format errors and I/O errors are reported separately. format_error is thrown directly with the stream state unchanged; I/O failures go through the stream's badbit and exception mask.

The version that writes to FILE* is in [iostream.format].

Unformatted output [ostream.unformatted]#

¶1 Unformatted output functions also construct a sentry first and, if it is true, make a best effort to generate output. If an exception is thrown during output, badbit is set, and the exception is rethrown if exceptions() contains badbit. They do not pad, do not look at width, and do not call widen.

  • ¶2–¶3 put(c) inserts the character c, setting badbit if it cannot.
  • ¶5 write(s, n) inserts characters from s one after another until n have been inserted; if an insertion fails, it sets badbit.
  • ¶7 flush(): if rdbuf() is non-null, constructs a sentry, and if it is true calls rdbuf()->pubsync(), setting badbit if that returns −1.

put and write have no overloads for signed char or unsigned char; a footnote points this out specifically.

Seeking [ostream.seeks]#

¶1 The positioning functions also construct a sentry first. ¶2 tellp() returns pos_type(-1) if fail() is true, otherwise rdbuf()->pubseekoff(0, cur, out). ¶3–¶6 seekp(pos) and seekp(off, dir) call pubseekpos or pubseekoff if fail() is false, setting failbit on failure.

Output manipulators [ostream.manip]#

Manipulator Effect
endl ¶2 os.put(os.widen('\n')), then os.flush()
ends ¶4 os.put(charT()), inserting a null character
flush ¶6 os.flush()
emit_on_flush ¶8 calls set_emit_on_sync(true) if os.rdbuf() is a basic_syncbuf, otherwise no effect
noemit_on_flush ¶10 same, calling set_emit_on_sync(false)
flush_emit ¶12 first os.flush(); if os.rdbuf() is a basic_syncbuf, then calls its emit() as an unformatted output function, setting badbit if it returns false

The uses of the last three manipulators are in [syncstream]. Determining whether rdbuf() is a basic_syncbuf<charT, traits, Allocator>* requires knowing Allocator, which cannot be deduced from os. The note in ¶8 suggests that implementations give basic_syncbuf an intermediate base class independent of the allocator, which manages this flag.

¶1 Each instantiation of these manipulators is a designated addressable function; a program may take their addresses.

endl is a newline plus a flush

For a stream writing to a file or pipe, one flush per line means one sync() per line, usually one system call. For bulk output use '\n' instead of std::endl so the stream buffer fills up before writing, and flush explicitly where needed (progress messages, the last log line before a crash). A prompt before interactive input does not need endl either: cin is tied to cout and flushes it automatically before reading ([iostream.objects]).

Rvalue stream insertion [ostream.rvalue]#

C++
template<class Ostream, class T>
  Ostream&& operator<<(Ostream&& os, const T& x);

¶1 Constraints: os << x is well-formed, and Ostream is publicly and unambiguously derived from ios_base. ¶2–¶3 The effect is to execute os << x and then return std::move(os).

It lets non-member inserters (strings, characters, user types) be used on temporary stream objects as well, and preserves the derived type, so you can write (std::ostringstream() << "id=" << 42).str().

Construction and destruction [ostream.cons]#

¶1–¶2 basic_ostream(sb) initializes the base class with basic_ios::init(sb), after which rdbuf() == sb. ¶3 The protected move constructor moves only the basic_ios state; the move assignment in [ostream.assign] is equivalent to swap.

¶4 The destructor performs no operations on rdbuf(), so destroying an ostream does not flush. Flushing is the responsibility of whoever owns the stream buffer; for example, ~basic_filebuf calls close().

Questions#

Question 1

A user type's operator<< throws midway. Is the part written to cerr (which has unitbuf on) flushed?

Answer

The outer sentry calls pubsync() only when !uncaught_exceptions() ([ostream.sentry]/4); it is destroyed during stack unwinding and does not flush. However, the standard inserters called inside the user's operator<< each constructed and normally destroyed their own sentries, and each of them flushed when it finished, so the part already written has usually been flushed.

Question 2

What does std::cout << std::setw(5); std::print(std::cout, "x"); std::cout << 'y'; output?

Answer

x y. print neither uses nor resets width ([ostream.formatted.print]/4 only inserts the formatted result unchanged), so the width of 5 is left for the following 'y', which is padded to 4 spaces plus y.

Question 3

Arithmetic inserters set badbit on failure, while the common rules say failure to generate output sets failbit. Is that a contradiction?

Answer

No. The common rules are the general case, and the specification of the arithmetic inserters ([ostream.inserters.arithmetic]/2) explicitly says badbit is set when failed is true. failed() is true for only one reason: when the ostreambuf_iterator wrote, sputc returned eof(), i.e. the stream buffer no longer accepts characters. That is a problem at the I/O layer, not an inability to format the value into characters, so it counts as badbit. Failures of put and write likewise set badbit.

Summary#

Function sentry Pads / resets width On failure
Arithmetic << yes handled by num_put badbit
Character, string << yes yes / yes null const char* is UB
<< streambuf* yes (unformatted) no nothing inserted: failbit; null sb: badbit
Manipulator << no no
put, write yes no badbit
flush yes no pubsync returns −1: badbit
print(os, ...) yes no / no format error throws format_error without setting bits; I/O failure sets badbit
sentry destructor with unitbuf and no uncaught exception, pubsync; on failure sets badbit, does not throw

In this clause

The authoritative text is eel.is/c++draft/output.streams (working draft 2026-08-23, commit c7015b485c). These are study notes that explain rather than quote; ¶ numbers follow the draft. Translated from the Chinese original. Last updated 2026-10-19.