Apache C++ Standard Library Reference Guide

## basic_ostream

Library: Input/output

    basic_ostream  basic_ios  ios_base

- Local Index
- Summary
- Synopsis
- Description
- Interface
- Member Types
- Nonmember Types
- Constructor
- Destructor
- Class sentry
- Formatted Output Functions: Inserters
- Unformatted Output Functions
- Nonmember Functions
- Formatting
- Example
- See Also
- Standards Conformance

### Local Index

#### Members

basic_ostream() bool() char_type flush() | int_type off_type operator<<() pos_type | put() seekp() sentry() tellp() | traits_type write() ~basic_ostream() ~sentry()

#### Non-Members

endl() ends() | flush() operator<<() | ostream wostream |

### Summary

Class that assists in formatting and writing output to sequences controlled by a stream buffer

### Synopsis

    #include <ostream>

    namespace std {
      template<class charT, class traits = char_traits<charT> >
      class basic_ostream;
    }

### Description

The class basic_ostream assists in formatting and writing output to sequences of characters controlled by a stream buffer. Two groups of functions share common properties, the formatted functions and the unformatted functions.

Both groups of functions insert output characters to basic_streambuf. They both begin by constructing an object of class basic_ostream::sentry and, if this object is in good state after construction, the function tries to perform the requested output. The sentry object performs exception-safe initialization, such as controlling the status of the stream or locking it in a multithread environment.

Some formatted output functions generate the requested output by converting a value from some scalar to text form and inserting the converted text in the output sequence. The conversion behavior is directly depend on the locale object being imbued in the stream.

### Interface

    namespace std {
      template <class charT, class traits = char_traits<charT> >
      class basic_ostream : virtual public basic_ios<charT,traits>
      {
       public:
        typedef charT                     char_type;
        typedef typename traits::int_type int_type;
        typedef typename traits::pos_type pos_type;
        typedef typename traits::off_type off_type;
        typedef traits                    traits_type;

        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<<(float f);
        basic_ostream& operator<<(double f);
        basic_ostream& operator<<(long double f);

        basic_ostream& operator<<(const void* p);
        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);
      };

      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 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*);
      }
    }

### Member Types

    char_type

The type `char_type` is a synonym for the template parameter `charT`.

    int_type

The type `int_type` is a synonym of type `traits::in_type`.

    off_type

The type `off_type` is a synonym of type `traits::off_type`.

    pos_type

The type `pos_type` is a synonym of type `traits::pos_type`.

    traits_type

The type `traits_type` is a synonym for the template parameter `traits`.

### Nonmember Types

    ostream

The type `ostream` is a specialization of class basic_ostream on type `char`:

`typedef basic_ostream<char> ostream;`

    wostream

The type `wostream` is a specialization of class basic_ostream on type `wchar_t`:

`typedef basic_ostream<wchar_t> wostream;`

### Constructor

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

Constructs an object of class basic_ostream, assigning initial values to the base class by calling:

`basic_ios<charT,traits>::init(sb)`;

### Destructor

    virtual ~basic_ostream();

Destroys an object of class basic_ostream.

### Class sentry

Interface

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

        private:
        sentry(const sentry&); // undefined
        sentry& operator=(const sentry&); // undefined
      };
    }

Constructor

    explicit sentry(basic_ostream<charT,traits>& os);

Prepares for formatted or unformatted output. If `os.tie()` is not a null pointer, the function synchronizes the output sequence with any associated stream. If after any preparation is completed, the `os.good()` is `true`, the sentry conversion function operator `bool()` returns `true`. Otherwise, it returns `false`. In a multithread environment, the sentry object constructor is responsible for locking the stream and the stream buffer associated with the stream.

Destructor

    ~sentry();

Destroys an object of class `sentry`. If the ios_base member function `flags() & unitbuf == true`, then flushes the buffer. In a multithread environment, the sentry object destructor is responsible for unlocking the stream and the stream buffer associated with the stream.

Operator

    operator bool();

If after any preparation is completed, the ios_base member function `good()` is `true`, the sentry conversion function operator `bool()` returns `true`, else it returns `false`.

### Formatted Output Functions: Inserters

Formatted output functions start by constructing an object of class sentry. If this object returns `true` when converted to a value of type `bool`, the function attempts to produce the requested output. If the generation fails, the function calls `setstate(ios::failbit)`, which might throw an exception. If an exception is thrown during output, `ios::badbit` is set in the stream object's error state without causing an `ios::failure` to be thrown.

If `(exceptions()&badbit) != 0`, the exception is rethrown. The sentry object is destroyed before the function exits. If no exception is thrown, the result of the formatted output function is `*this`.

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

Calls `pf(*this)`, then returns `*this`. See, for example, the function signature `endl(basic_ostream&)`.

    basic_ostream&
    operator<<(basic_ios<char_type, traits_type>&
                 (*pf)(basic_ios<char_type, traits_type>&));

Calls `pf(*this)`, then returns `*this`.

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

Calls `pf(*this)`, then returns `*this`. For example, see the function signature `dec(ios_base&)`.

    basic_ostream&
    operator<<(bool n);

Converts the boolean value `n` and outputs it into the basic_ostream object's buffer. If the ios_base member function `flag() & ios_base::boolalpha` is `false`, it tries to write an integer value, which must be `0` or `1`. If the `boolalpha` flag is `true`, it writes characters according to the locale function `numpunct<>::truename()` or `numpunct<>::falsename()`.

    basic_ostream&
    operator<<(short n);

Converts the `signed short` integer `n`, outputs it into the stream buffer, and returns `*this`.

    basic_ostream&
    operator<<(unsigned short n);

Converts the `unsigned short` integer `n`, outputs it into the stream buffer, and returns `*this`.

    basic_ostream&
    operator<<(int n);

Converts the`signed integer n`, outputs it into the stream buffer, and returns `*this`.

    basic_ostream&
    operator<<(unsigned int n);

Converts the `unsigned integer n`, outputs it into the stream buffer, and returns `*this`.

    basic_ostream&
    operator<<(long n);

Converts the `signed long` integer `n`, outputs it into the stream buffer, and returns `*this`.

    basic_ostream&
    operator<<(unsigned long n);

Converts the `unsigned long` integer n, outputs it into the stream buffer, and returns `*this`.

    basic_ostream&
    operator<<(float f);

Converts the `float f`, outputs it into the stream buffer, and returns `*this`.

    basic_ostream&
    operator<<(double f);

Converts the `double f`, outputs it into the stream buffer, and returns `*this`.

    basic_ostream&
    operator<<(long double f);

Converts the `long double f`, outputs it into the stream buffer, and returns `*this`.

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

Converts the `pointer p`, outputs it into the stream buffer, and returns `*this`.

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

If `sb` is null, calls the basic_ios member function `setstate(badbit)`. Otherwise, gets characters from `sb` and inserts them into the stream buffer until any of the following occurs:

- an end-of-file on the input sequence

- a failure when inserting into the output sequence

- an exception while getting a character from `sb`

If the function inserts no characters, or if it stops because an exception is thrown while extracting a character, it calls the basic_ios member function `setstate(failbit)`. If an exception is thrown while extracting a character, it is rethrown.

### Unformatted Output Functions

    basic_ostream&
    flush();

If `rdbuf()` is not a null pointer, calls `rdbuf()->pubsync()` and returns `*this`. If that function returns `-1`, calls `setstate(badbit)`.

    basic_ostream&
    put(char_type c);

Inserts the character `c`. If the operation fails, calls the basic_ios member function `setstate(badbit)`.

    basic_ostream&
    seekp(pos_type pos);

If the basic_ios member function `fail()` returns `false`, executes `rdbuf()->pubseekpos(pos)`, which positions the current pointer of the output sequence at the position designated by `pos`. If positioning fails, calls the basic_ios member function `setstate(failbit)`.

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

If the basic_ios member function `fail()` returns `false`, executes `rdbuf()->pubseekpos(off,dir)`, which positions the current pointer of the output sequence at the position designated by `off` and `dir`. If positioning fails, calls the basic_ios member function `setstate(failbit)`.

    pos_type
    tellp();

If the basic_ios member function `fail()` returns `true`, `tellp()` returns `pos_type(off_type(-1))` to indicate failure. Otherwise it returns the current position of the output sequence by calling `rdbuf()-> pubseekoff(0,cur, out)`.

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

Obtains characters to insert from successive locations of an array whose first element is designated by `s`. Characters are inserted until either of the following occurs:

- `n` characters are inserted

- inserting into the output sequence fails

In the second case, the function calls the basic_ios member function `setstate(badbit)`. The function returns `*this`.

### Nonmember Functions

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

Outputs a `newline` character by calling `os.put(os.widen ('\n'))`, flushes the buffer, and returns `os`.

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

Inserts a null character, `charT()`, into the output sequence, then returns `os`.

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

Flushes the buffer, then returns `os`.

    template<class charT, class traits>
    basic_ostream<charT, traits>&
    operator<<(basic_ostream<charT, traits>& os, charT c);
    template<class charT, class traits>
    basic_ostream<charT, traits>&
    operator<<(basic_ostream<charT, traits>& os, char c);
    template<class traits>
    basic_ostream<char, traits>&
    operator<<(basic_ostream<char, traits>& os, char c);
    template<class traits>
    basic_ostream<char, traits>&
    operator<<(basic_ostream<char, traits>& os, signed char c);
    template<class traits>
    basic_ostream<char, traits>&
    operator<<(basic_ostream<char, traits>& os, unsigned char c);

Outputs the character `c` and any required padding into the basic_ostream object's buffer. If the type of `c` is `char` and it doesn't match `char_type`, the function calls `os.widen (c)` before inserting the character. Before returning, the function calls `os.width (0)`.

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

After constructing a sentry object the function inserts `traits::length(s)` characters starting at `s` plus any required padding into `os`. Characters starting at `s` are widened by calling `os.widen (*s)`. Before returning, the function calls `os.width (0)`.

### Formatting

The formatting is done through member functions or manipulators.

#### Table 11: Formatting manipulators and functions for basic_ostream

Manipulators | Member Functions
`showpos` | `setf(ios_base::showpos)`
`noshowpos` | `unsetf(ios_base::showpos)`
`showbase` | `setf(ios_base::showbase)`
`noshowbase` | `unsetf(ios_base::showbase)`
`uppercase` | `setf(ios_base::uppercase)`
`nouppercase` | `unsetf(ios_base::uppercase)`
`showpoint` | `setf(ios_base::showpoint)`
`noshowpoint` | `unsetf(ios_base::showpoint)`
`boolalpha` | `setf(ios_base::boolalpha)`
`noboolalpha` | `unsetf(ios_base::boolalpha)`
`unitbuf` | `setf(ios_base::unitbuf)`
`nounitbuf` | `unsetf(ios_base::unitbuf)`
`internal` | `setf(ios_base::internal, ios_base::adjustfield)`
`left` | `setf(ios_base::left, ios_base::adjustfield)`
`right` | `setf(ios_base::right, ios_base::adjustfield)`
`dec` | `setf(ios_base::dec, ios_base::basefield)`
`hex` | `setf(ios_base::hex, ios_base::basefield)`
`oct` | `setf(ios_base::oct, ios_base::basefield)`
`fixed` | `setf(ios_base::fixed, ios_base::floatfield)`
`scientific` | `setf(ios_base::scientific, ios_base::floatfield)`
`resetiosflags` `(ios_base::fmtflags flag)` | `setf(0,flag)`
`setiosflags` `(ios_base::fmtflags flag)` | `setf(flag)`
`setbase(int base)` | see above
`setfill(char_type c)` | `fill(c)`
`setprecision(int n)` | `precision(n)`
`setw(int n)` | `width(n)`

The meaning of the manipulators is as follows:

`showpos` | Generates a `+` sign in nonnegative generated numeric output
`showbase` | Generates a prefix indicating the numeric base of generated integer output
`uppercase` | Replaces certain lowercase letters with their uppercase equivalents in generated output
`showpoint` | Generates a decimal-point character unconditionally in generated floating-point output
`boolalpha` | Inserts and extracts the `bool` type in alphabetic format
`unitbuf` | Flushes output after each output operation
`internal` | Adds fill characters at a designated internal point in certain generated output. If no such point is designated, it's identical to `right`.
`left` | Adds fill characters on the right (final positions) of certain generated output
`right` | Adds fill characters on the left (initial positions) of certain generated output
`dec` | Converts integer input or generates integer output in decimal base
`hex` | Converts integer input or generates integer output in hexadecimal base
`oct` | Converts integer input or generates integer output in octal base
`fixed` | Generates floating-point output in fixed-point notation
`scientific` | Generates floating-point output in scientific notation
`resetiosflags(ios_base::fmtflags flag)` | Resets the `fmtflags` field `flag`
`setiosflags(ios_base::fmtflags flag)` | Sets up the flag `flag`.
`setbase(int base)` | Converts integer input or generates integer output in base `base`. The parameter `base` can be 8, 10 or 16.
`setfill(char_type c)` | Sets the character used to pad (fill) an output conversion to the specified field width
`setprecision(int n)` | Sets the precision (number of digits after the decimal point) to generate on certain output conversions
`setw(int n)` | Sets the field width (number of characters) to generate on certain output conversions

### Example

    //
    //  ostream1.cpp
    //

    #include <iostream>   // for cout, endl, hex, oct
    #include <sstream>    // for istringstream
    #include <iomanip>    // for setfill, setprecision, setw

    int main ( )
    {
        // create a read/write stringbuf object on tiny char
        // and attach it to an istringstream object
        std::istringstream in (std::ios::in | std::ios::out);

        // tie the ostream object to the istringstream object
        std::ostream out (in.rdbuf ());

        out << "test beginning !" << std::endl;

        // output an int value in hexadecimal
        const int i = 22;
        out << std::hex << i << std::endl;

        // set the field width to 10, the padding character
        // to '@' and output i in octal notation
        out << std::setw (10) << std::oct
            << std::setfill ('@') << i << std::endl;

        // output a float with precision set to 2 digits
        // after the separator
        const float f = 3.14159123;
        out << std::setprecision (3) << f << std::endl;

        const char s[] = "Why, one can hear the grass growing!";

        // output the 17 first characters of s
        out.write (s, 17);

        // output a newline character
        out.put ('\n');

        // output s
        out << s << std::endl;

        // output the entire contents of the buffer
        // to standard output
        std::cout << in.rdbuf();

        return 0;
    }

    Program Output:

    test beginning !
    16
    @@@@@@@@26
    3.14
    Why, one can hear
    Why, one can hear the grass growing!

    //
    //  ostream2.cpp
    //

    #include <iostream>   // for wcout, endl
    #include <sstream>    // for wistringstream

    int main ()
    {
        const float f = 3.14159;

        const wchar_t s[] = { 'K', 'e', 'n', 'a', 'v',
                              'o', ' ', '!', '\0' };

        // create a read/write stringbuf object on wide char
        // and attach it to an wistringstream object
        std::wistringstream in (std::wios::in | std::wios::out);

        // tie the wostream object to the wistringstream object
        std::wostream out (in.rdbuf ());

        out << L"test beginning !" << std::endl;
        out.setf (std::wios::fixed, std::wios::floatfield);

        // output f in fixed format
        out << f << std::endl;

        // store the current put-pointer position
        std::wostream::pos_type pos = out.tellp ();

        // output s
        out << s << std::endl;

        // output the all buffer to standard output
        std::wcout << in.rdbuf () << std::endl;

        // position the get-pointer
        in.seekg (pos);

        // output s
        std::wcout << in.rdbuf () << std::endl;

        return 0;
    }

    Program Output:

    test beginning !
    3.141593
    Kenavo !

    Kenavo !

### See Also

char_traits, ios_base, basic_ios, basic_streambuf, basic_iostream

### Standards Conformance

ISO/IEC 14882:1998 -- International Standard for Information Systems --Programming Language C++, Section 27.6.2.1