[output.streams] (original) (raw)

31 Input/output library [input.output]

31.7 Formatting and manipulators [iostream.format]

31.7.6 Output streams [output.streams]

31.7.6.1 General [output.streams.general]

The header defines a class template and several function templates that control output to a stream buffer, along with a function template that inserts into stream rvalues.

31.7.6.2 Class template basic_ostream [ostream]

31.7.6.2.1 General [ostream.general]

When a function has a parameter type extended-floating-point-type, the implementation provides overloads for all cv-unqualified extended floating-point types ([basic.fundamental]).

namespace std { template<class charT, class traits = char_traits<charT>> class basic_ostream : virtual public basic_ios<charT, traits> { public: using char_type = charT;using int_type = typename traits::int_type;using pos_type = typename traits::pos_type;using off_type = typename traits::off_type;using traits_type = traits;explicit basic_ostream(basic_streambuf<char_type, traits>* sb);virtual ~basic_ostream();class sentry; basic_ostream& operator<<(basic_ostream& (*pf)(basic_ostream&)); basic_ostream& operator<<(basic_ios<charT, traits>& (*pf)(basic_ios<charT, traits>&)); basic_ostream& operator<<(ios_base& (*pf)(ios_base&)); basic_ostream& operator<<(bool n); basic_ostream& operator<<(short n); basic_ostream& operator<<(unsigned short n); basic_ostream& operator<<(int n); basic_ostream& operator<<(unsigned int n); basic_ostream& operator<<(long n); basic_ostream& operator<<(unsigned long n); basic_ostream& operator<<(long long n); basic_ostream& operator<<(unsigned long long n); basic_ostream& operator<<(float f); basic_ostream& operator<<(double f); basic_ostream& operator<<(long double f); basic_ostream& operator<<(_extended-floating-point-type_ f); basic_ostream& operator<<(const void* p); basic_ostream& operator<<(const volatile void* p); basic_ostream& operator<<(nullptr_t); basic_ostream& operator<<(basic_streambuf<char_type, traits>* sb); basic_ostream& put(char_type c); basic_ostream& write(const char_type* s, streamsize n); basic_ostream& flush(); pos_type tellp(); basic_ostream& seekp(pos_type); basic_ostream& seekp(off_type, ios_base::seekdir);protected: basic_ostream(const basic_ostream&) = delete; basic_ostream(basic_ostream&& rhs); basic_ostream& operator=(const basic_ostream&) = delete; basic_ostream& operator=(basic_ostream&& rhs);void swap(basic_ostream& rhs);};template<class charT, class traits> basic_ostream<charT, traits>& operator<<(basic_ostream<charT, traits>&, charT);template<class charT, class traits> basic_ostream<charT, traits>& operator<<(basic_ostream<charT, traits>&, char);template<class traits> basic_ostream<char, traits>& operator<<(basic_ostream<char, traits>&, char);template<class traits> basic_ostream<char, traits>& operator<<(basic_ostream<char, traits>&, signed char);template<class traits> basic_ostream<char, traits>& operator<<(basic_ostream<char, traits>&, unsigned char);template<class traits> basic_ostream<char, traits>& operator<<(basic_ostream<char, traits>&, wchar_t) = delete;template<class traits> basic_ostream<char, traits>& operator<<(basic_ostream<char, traits>&, char8_t) = delete;template<class traits> basic_ostream<char, traits>& operator<<(basic_ostream<char, traits>&, char16_t) = delete;template<class traits> basic_ostream<char, traits>& operator<<(basic_ostream<char, traits>&, char32_t) = delete;template<class traits> basic_ostream<wchar_t, traits>& operator<<(basic_ostream<wchar_t, traits>&, char8_t) = delete;template<class traits> basic_ostream<wchar_t, traits>& operator<<(basic_ostream<wchar_t, traits>&, char16_t) = delete;template<class traits> basic_ostream<wchar_t, traits>& operator<<(basic_ostream<wchar_t, traits>&, char32_t) = delete;template<class charT, class traits> basic_ostream<charT, traits>& operator<<(basic_ostream<charT, traits>&, const charT*);template<class charT, class traits> basic_ostream<charT, traits>& operator<<(basic_ostream<charT, traits>&, const char*);template<class traits> basic_ostream<char, traits>& operator<<(basic_ostream<char, traits>&, const char*);template<class traits> basic_ostream<char, traits>& operator<<(basic_ostream<char, traits>&, const signed char*);template<class traits> basic_ostream<char, traits>& operator<<(basic_ostream<char, traits>&, const unsigned char*);template<class traits> basic_ostream<char, traits>& operator<<(basic_ostream<char, traits>&, const wchar_t*) = delete;template<class traits> basic_ostream<char, traits>& operator<<(basic_ostream<char, traits>&, const char8_t*) = delete;template<class traits> basic_ostream<char, traits>& operator<<(basic_ostream<char, traits>&, const char16_t*) = delete;template<class traits> basic_ostream<char, traits>& operator<<(basic_ostream<char, traits>&, const char32_t*) = delete;template<class traits> basic_ostream<wchar_t, traits>& operator<<(basic_ostream<wchar_t, traits>&, const char8_t*) = delete;template<class traits> basic_ostream<wchar_t, traits>& operator<<(basic_ostream<wchar_t, traits>&, const char16_t*) = delete;template<class traits> basic_ostream<wchar_t, traits>& operator<<(basic_ostream<wchar_t, traits>&, const char32_t*) = delete;}

The class templatebasic_ostreamdefines a number of member function signatures that assist in formatting and writing output to output sequences controlled by a stream buffer.

Two groups of member function signatures share common properties: theformatted output functions(orinserters) and theunformatted output functions.Both groups of output functions generate (orinsert) outputcharactersby actions equivalent to callingrdbuf()->sputc(int_type).

They may use other public members ofbasic_ostreamexcept that they shall not invoke any virtual members ofrdbuf()exceptoverflow(),xsputn(), andsync().

If one of these called functions throws an exception, then unless explicitly noted otherwise the output function setsbadbitin the error state.

Ifbadbitis set inexceptions(), the output function rethrows the exception without completing its actions, otherwise it does not throw anything and proceeds as if the called function had returned a failure indication.

[Note 1:

The deleted overloads of operator<<prevent formatting characters as integers and strings as pointers.

— _end note_]

31.7.6.2.2 Constructors [ostream.cons]

explicit basic_ostream(basic_streambuf<charT, traits>* sb);

Effects: Initializes the base class subobject withbasic_ios<charT, traits>​::​init(sb) ([basic.ios.cons]).

Postconditions: rdbuf() == sb.

basic_ostream(basic_ostream&& rhs);

Effects: Move constructs from the rvalue rhs.

This is accomplished by default constructing the base class and callingbasic_ios<charT, traits>​::​move(rhs) to initialize the base class.

virtual ~basic_ostream();

Remarks: Does not perform any operations onrdbuf().

31.7.6.2.3 Assignment and swap [ostream.assign]

basic_ostream& operator=(basic_ostream&& rhs);

Effects: Equivalent to swap(rhs).

void swap(basic_ostream& rhs);

Effects: Calls basic_ios<charT, traits>​::​swap(rhs).

31.7.6.2.4 Class basic_ostream​::​sentry [ostream.sentry]

namespace std { template<class charT, class traits> class basic_ostream<charT, traits>::sentry { bool ok_; public: explicit sentry(basic_ostream& os);~sentry();explicit operator bool() const { return ok_; } sentry(const sentry&) = delete; sentry& operator=(const sentry&) = delete;};}

The classsentrydefines a class that is responsible for doing exception safe prefix and suffix operations.

explicit sentry(basic_ostream& os);

Ifos.good()is nonzero, prepares for formatted or unformatted output.

Ifos.tie()is not a null pointer, callsos.tie()->flush().284

If, after any preparation is completed,os.good()istrue,ok_ == trueotherwise,ok_ == false.

During preparation, the constructor may callsetstate(failbit)(which may throwios_base​::​​failure ([iostate.flags])).285

If(os.flags() & ios_base​::​unitbuf) && !uncaught_exceptions() && os.good()istrue, callsos.rdbuf()->pubsync().

If that function returns , sets badbit inos.rdstate() without propagating an exception.

explicit operator bool() const;

31.7.6.2.5 Seek members [ostream.seeks]

Each seek member function begins execution by constructing an object of class sentry.

It returns by destroying the sentry object.

Returns: Iffail() != false, returnspos_type(-1)to indicate failure.

Otherwise, returnsrdbuf()->​pubseekoff(​0, cur, out).

basic_ostream& seekp(pos_type pos);

Effects: Iffail() != true, executesrdbuf()->pubseekpos(pos, ios_base​::​out).

In case of failure, the function callssetstate(failbit)(which may throwios_base​::​failure).

basic_ostream& seekp(off_type off, ios_base::seekdir dir);

Effects: Iffail() != true, executesrdbuf()->pubseekoff(off, dir, ios_base​::​out).

In case of failure, the function calls setstate(failbit)(which may throw ios_base​::​failure).

31.7.6.3 Formatted output functions [ostream.formatted]

31.7.6.3.1 Common requirements [ostream.formatted.reqmts]

Each formatted output function begins execution by constructing an object of classsentry.

If that object returnstruewhen converted to a value of typebool, the function endeavors to generate the requested output.

If the generation fails, then the formatted output function doessetstate(ios_base​::​failbit), which can throw an exception.

If an exception is thrown during output, thenios_base​::​badbitis set286in*this's error state.

If(exceptions() & badbit) != 0then the exception is rethrown.

Whether or not an exception is thrown, thesentryobject is destroyed before leaving the formatted output function.

If no exception is thrown, the result of the formatted output function is*this.

The descriptions of the individual formatted output functions describe how they perform output and do not mention thesentryobject.

If a formatted output function of a stream os determines padding, it does so as follows.

Given a charT character sequence seq wherecharT is the character container type of the stream, if the length of seq is less than os.width(), then enough copies ofos.fill() are added to this sequence as necessary to pad to a width of os.width() characters.

If(os.flags() & ios_base​::​adjustfield) == ios_base​::​left istrue, the fill characters are placed after the character sequence; otherwise, they are placed before the character sequence.

31.7.6.3.2 Arithmetic inserters [ostream.inserters.arithmetic]

basic_ostream& operator<<(bool val); basic_ostream& operator<<(short val); basic_ostream& operator<<(unsigned short val); basic_ostream& operator<<(int val); basic_ostream& operator<<(unsigned int val); basic_ostream& operator<<(long val); basic_ostream& operator<<(unsigned long val); basic_ostream& operator<<(long long val); basic_ostream& operator<<(unsigned long long val); basic_ostream& operator<<(float val); basic_ostream& operator<<(double val); basic_ostream& operator<<(long double val); basic_ostream& operator<<(const void* val);

Effects: The classesnum_get<>andnum_put<>handle locale-dependent numeric formatting and parsing.

These inserter functions use the imbuedlocalevalue to perform numeric formatting.

When valis of typebool,long,unsigned long,long long, unsigned long long,double,long double, orconst void*, the formatting conversion occurs as if it performed the following code fragment:bool failed = use_facet<num_put<charT, ostreambuf_iterator<charT, traits>>>( getloc()).put(*this, *this, fill(), val).failed();

When val is of typeshortthe formatting conversion occurs as if it performed the following code fragment:ios_base::fmtflags baseflags = ios_base::flags() & ios_base::basefield;bool failed = use_facet<num_put<charT, ostreambuf_iterator<charT, traits>>>( getloc()).put(*this, *this, fill(), baseflags == ios_base::oct || baseflags == ios_base::hex? static_cast<long>(static_cast<unsigned short>(val)) : static_cast<long>(val)).failed();

When val is of typeintthe formatting conversion occurs as if it performed the following code fragment:ios_base::fmtflags baseflags = ios_base::flags() & ios_base::basefield;bool failed = use_facet<num_put<charT, ostreambuf_iterator<charT, traits>>>( getloc()).put(*this, *this, fill(), baseflags == ios_base::oct || baseflags == ios_base::hex? static_cast<long>(static_cast<unsigned int>(val)) : static_cast<long>(val)).failed();

When val is of typeunsigned shortorunsigned intthe formatting conversion occurs as if it performed the following code fragment:bool failed = use_facet<num_put<charT, ostreambuf_iterator<charT, traits>>>( getloc()).put(*this, *this, fill(), static_cast<unsigned long>(val)).failed();

When val is of typefloatthe formatting conversion occurs as if it performed the following code fragment:bool failed = use_facet<num_put<charT, ostreambuf_iterator<charT, traits>>>( getloc()).put(*this, *this, fill(), static_cast<double>(val)).failed();

The first argument provides an object of theostreambuf_iterator<>class which is an iterator for class basic_ostream<>.

It bypassesostreams and usesstreambufs directly.

Classlocalerelies on these types as its interface to iostreams, since for flexibility it has been abstracted away from direct dependence onostream.

The second parameter is a reference to the base class subobject of typeios_base.

It provides formatting specifications such as field width, and a locale from which to obtain other facets.

Iffailedistruethen doessetstate(badbit), which may throw an exception, and returns.

basic_ostream& operator<<(const volatile void* p);

Effects: Equivalent to: return operator<<(const_cast<const void*>(p));

basic_ostream& operator<<(_extended-floating-point-type_ val);

Effects: If the floating-point conversion rank of _extended-floating-point-type_is less than or equal to that of double, the formatting conversion occurs as if it performed the following code fragment:bool failed = use_facet<num_put<charT, ostreambuf_iterator<charT, traits>>>( getloc()).put(*this, *this, fill(), static_cast<double>(val)).failed();

Otherwise, if the floating-point conversion rank of _extended-floating-point-type_is less than or equal to that of long double, the formatting conversion occurs as if it performed the following code fragment:bool failed = use_facet<num_put<charT, ostreambuf_iterator<charT, traits>>>( getloc()).put(*this, *this, fill(), static_cast<long double>(val)).failed();

Otherwise, an invocation of the operator function is conditionally supported with implementation-defined semantics.

If failed is true then does setstate(badbit), which may throw an exception, and returns.

31.7.6.3.3 basic_ostream​::​operator<< [ostream.inserters]

basic_ostream& operator<<(basic_ostream& (*pf)(basic_ostream&));

Effects: None.

Does not behave as a formatted output function (as described in [ostream.formatted.reqmts]).

basic_ostream& operator<<(basic_ios<charT, traits>& (*pf)(basic_ios<charT, traits>&));

Effects: Callspf(*this).

This inserter does not behave as a formatted output function (as described in [ostream.formatted.reqmts]).

basic_ostream& operator<<(ios_base& (*pf)(ios_base&));

Effects: Callspf(*this).

This inserter does not behave as a formatted output function (as described in [ostream.formatted.reqmts]).

basic_ostream& operator<<(basic_streambuf<charT, traits>* sb);

Effects: Behaves as an unformatted output function ([ostream.unformatted]).

After the sentry object is constructed, ifsb is null callssetstate(badbit)(which may throwios_base​::​failure).

Gets characters from sband inserts them in*this.

Characters are read from sband inserted until any of the following occurs:

If the function inserts no characters, it callssetstate(failbit)(which may throwios_base​::​​failure ([iostate.flags])).

If an exception was thrown while extracting a character, the function setsfailbitin the error state, and iffailbitis set inexceptions()the caught exception is rethrown.

basic_ostream& operator<<(nullptr_t);

Effects: Equivalent to:return *this << s;where s is animplementation-definedNTCTS.

31.7.6.3.4 Character inserter function templates [ostream.inserters.character]

template<class charT, class traits> basic_ostream<charT, traits>& operator<<(basic_ostream<charT, traits>& out, charT c);template<class charT, class traits> basic_ostream<charT, traits>& operator<<(basic_ostream<charT, traits>& out, char c);// specialization template<class traits> basic_ostream<char, traits>& operator<<(basic_ostream<char, traits>& out, char c);// signed and unsigned template<class traits> basic_ostream<char, traits>& operator<<(basic_ostream<char, traits>& out, signed char c);template<class traits> basic_ostream<char, traits>& operator<<(basic_ostream<char, traits>& out, unsigned char c);

Effects: Behaves as a formatted output functionof out.

Constructs a character sequence seq.

If c has typecharand the character container type of the stream is notchar, then seq consists ofout.widen(c); otherwise seq consists ofc.

Determines padding for seq as described in [ostream.formatted.reqmts].

Inserts seq intoout.

Calls os.width(0).

template<class charT, class traits> basic_ostream<charT, traits>& operator<<(basic_ostream<charT, traits>& out, const charT* s);template<class charT, class traits> basic_ostream<charT, traits>& operator<<(basic_ostream<charT, traits>& out, const char* s);template<class traits> basic_ostream<char, traits>& operator<<(basic_ostream<char, traits>& out, const char* s);template<class traits> basic_ostream<char, traits>& operator<<(basic_ostream<char, traits>& out, const signed char* s);template<class traits> basic_ostream<char, traits>& operator<<(basic_ostream<char, traits>& out,const unsigned char* s);

Preconditions: s is not a null pointer.

Effects: Behaves like a formatted inserter (as described in [ostream.formatted.reqmts]) of out.

Creates a character sequence seq of n characters starting at s, each widened usingout.widen() ([basic.ios.members]), where n is the number that would be computed as if by:

Determines padding for seq as described in [ostream.formatted.reqmts].

Inserts seq intoout.

Calls width(0).

31.7.6.3.5 Print [ostream.formatted.print]

template<class... Args> void print(ostream& os, format_string<Args...> fmt, Args&&... args);

Effects: If the ordinary literal encoding ([lex.charset]) is UTF-8, equivalent to:vprint_unicode(os, fmt.str, make_format_args(args...));

Otherwise, equivalent to:vprint_nonunicode(os, fmt.str, make_format_args(args...));

template<class... Args> void println(ostream& os, format_string<Args...> fmt, Args&&... args);

Effects: Equivalent to:print(os, "{}\n", format(os.getloc(), fmt, std::forward<Args>(args)...));

void println(ostream& os);

Effects: Equivalent to:print(os, "\n");

void vprint_unicode(ostream& os, string_view fmt, format_args args);void vprint_nonunicode(ostream& os, string_view fmt, format_args args);

Effects: Behaves as a formatted output function ([ostream.formatted.reqmts]) of os, except that:

After constructing a sentry object, the function initializes a variable with automatic storage duration viastring out = vformat(os.getloc(), fmt, args);

If writing to the terminal or inserting into os fails, calls os.setstate(ios_base​::​badbit)(which may throw ios_base​::​failure).

Recommended practice: For vprint_unicode, if invoking the native Unicode API requires transcoding, implementations should substitute invalid code units with U+fffd replacement character per the Unicode Standard, Chapter 3.9 U+fffd Substitution in Conversion.

31.7.6.4 Unformatted output functions [ostream.unformatted]

Each unformatted output function begins execution by constructing an object of classsentry.

If that object returnstrue, while converting to a value of typebool, the function endeavors to generate the requested output.

If an exception is thrown during output, thenios_base​::​badbitis set289in*this's error state.

If(exceptions() & badbit) != 0then the exception is rethrown.

In any case, the unformatted output function ends by destroying thesentry object, then, if no exception was thrown, returning the value specified for the unformatted output function.

basic_ostream& put(char_type c);

Effects: Behaves as an unformatted output function (as described above).

After constructing a sentryobject, inserts the character c, if possible.290

Otherwise, callssetstate(badbit)(which may throwios_base​::​failure ([iostate.flags])).

basic_ostream& write(const char_type* s, streamsize n);

Effects: Behaves as an unformatted output function (as described above).

After constructing a sentryobject, obtains characters to insert from successive locations of an array whose first element is designated bys.291

Characters are inserted until either of the following occurs:

Effects: Behaves as an unformatted output function (as described above).

Ifrdbuf()is not a null pointer, constructs a sentry object.

If that object returns true when converted to a value of type bool the function callsrdbuf()->pubsync().

If that function returns callssetstate(badbit)(which may throwios_base​::​failure ([iostate.flags])).

Otherwise, if the sentry object returns false, does nothing.

31.7.6.5 Standard basic_ostream manipulators [ostream.manip]

Each instantiation of any of the function templates specified in this subclause is a designated addressable function ([namespace.std]).

template<class charT, class traits> basic_ostream<charT, traits>& endl(basic_ostream<charT, traits>& os);

Effects: Callsos.put(os.widen('\n')), thenos.flush().

template<class charT, class traits> basic_ostream<charT, traits>& ends(basic_ostream<charT, traits>& os);

Effects: Inserts a null character into the output sequence: callsos.put(charT()).

template<class charT, class traits> basic_ostream<charT, traits>& flush(basic_ostream<charT, traits>& os);

Effects: Callsos.flush().

template<class charT, class traits> basic_ostream<charT, traits>& emit_on_flush(basic_ostream<charT, traits>& os);

Effects: If os.rdbuf() is abasic_syncbuf<charT, traits, Allocator>*, called buf for the purpose of exposition, calls buf->set_emit_on_sync(true).

Otherwise this manipulator has no effect.

[Note 1:

To work around the issue that theAllocator template argument cannot be deduced, implementations can introduce an intermediate base class to basic_syncbuf that manages its emit-on-sync flag.

— _end note_]

template<class charT, class traits> basic_ostream<charT, traits>& noemit_on_flush(basic_ostream<charT, traits>& os);

Effects: If os.rdbuf() is abasic_syncbuf<charT, traits, Allocator>*, called buf for the purpose of exposition, calls buf->set_emit_on_sync(false).

Otherwise this manipulator has no effect.

template<class charT, class traits> basic_ostream<charT, traits>& flush_emit(basic_ostream<charT, traits>& os);

Effects: Calls os.flush().

Then, if os.rdbuf() is abasic_syncbuf<charT, traits, Allocator>*, called buf for the purpose of exposition, behaves as an unformatted output function ([ostream.unformatted]) of os.

After constructing a sentry object, calls buf->emit().

If that call returns false, calls os.setstate(ios_base​::​badbit).

31.7.6.6 Rvalue stream insertion [ostream.rvalue]

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

Constraints: The expression os << x is well-formed when treated as an unevaluated operand andOstream is publicly and unambiguously derived from ios_base.

Effects: As if by: os << x;

Returns: std​::​move(os).