Search

18.3 — Output with ostream and ios

In this section, we will look at various aspects of the iostream output class (ostream).

Note: All of the I/O functionality in this lesson lives in the std namespace. That means all I/O objects and functions either have to be prefixed with “std::”, or the “using namespace std;” statement has to be used.

The insertion operator

The insertion operator (<<) is used to put information into an output stream. C++ has predefined insertion operations for all of the built-in data types, and you've already seen how you can overload the insertion operator for your own classes.

In the lesson on streams, you saw that both istream and ostream were derived from a class called ios. One of the jobs of ios (and ios_base) is to control the formatting options for output.

Formatting

There are two ways to change the formatting options: flags, and manipulators. You can think of flags as boolean variables that can be turned on and off. Manipulators are objects placed in a stream that affect the way things are input and output.

To switch a flag on, use the setf() function, with the appropriate flag as a parameter. For example, by default, C++ does not print a + sign in front of positive numbers. However, by using the ios::showpos flag, we can change this behavior:

This results in the following output:

+27

It is possible to turn on multiple ios flags at once using the OR (|) operator:

To turn a flag off, use the unsetf() function:

This results in the following output:

+27
28

There’s one other bit of trickiness when using setf() that needs to be mentioned. Many flags belong to groups, called format groups. A format group is a group of flags that perform similar (sometimes mutually exclusive) formatting options. For example, a format group named “basefield” contains the flags “oct”, “dec”, and “hex”, which controls the base of integral values. By default, the “dec” flag is set. Consequently, if we do this:

We get the following output:

27

It didn’t work! The reason why is because setf() only turns flags on -- it isn’t smart enough to turn mutually exclusive flags off. Consequently, when we turned ios::hex on, ios::dec was still on, and ios::dec apparently takes precedence. There are two ways to get around this problem.

First, we can turn off ios::dec so that only ios::hex is set:

Now we get output as expected:

1b

The second way is to use a different form of setf() that takes two parameters: the first parameter is the flag to set, and the second is the formatting group it belongs to. When using this form of setf(), all of the flags belonging to the group are turned off, and only the flag passed in is turned on. For example:

This also produces the expected output:

1b

Using setf() and unsetf() tends to be awkward, so C++ provides a second way to change the formatting options: manipulators. The nice thing about manipulators is that they are smart enough to turn on and off the appropriate flags. Here is an example of using some manipulators to change the base:

This program produces the output:

1b
1c
29

In general, using manipulators is much easier than setting and unsetting flags. Many options are available via both flags and manipulators (such as changing the base), however, other options are only available via flags or via manipulators, so it’s important to know how to use both.

Useful formatters

Here is a list of some of the more useful flags, manipulators, and member functions. Flags live in the ios class, manipulators live in the std namespace, and the member functions live in the ostream class.

Group Flag Meaning
boolalpha If set, booleans print “true” or “false”. If not set, booleans print 0 or 1

Manipulator Meaning
boolalpha Booleans print “true” or “false”
noboolalpha Booleans print 0 or 1 (default)

Example:

Result:

0 1
true false
0 1
true false
Group Flag Meaning
showpos If set, prefix positive numbers with a +

Manipulator Meaning
showpos Prefixes positive numbers with a +
noshowpos Doesn’t prefix positive numbers with a +

Example:

Result:

5
+5
5
+5
Group Flag Meaning
uppercase If set, uses upper case letters

Manipulator Meaning
uppercase Uses upper case letters
nouppercase Uses lower case letters

Example:

Result:

1.23457e+007
1.23457E+007
1.23457e+007
1.23457E+007
Group Flag Meaning
basefield dec Prints values in decimal (default)
basefield hex Prints values in hexadecimal
basefield oct Prints values in octal
basefield (none) Prints values according to leading characters of value

Manipulator Meaning
dec Prints values in decimal
hex Prints values in hexadecimal
oct Prints values in octal

Example:

Result:

27
27
33
1b
27
33
1b

By now, you should be able to see the relationship between setting formatting via flag and via manipulators. In future examples, we will use manipulators unless they are not available.

Precision, notation, and decimal points

Using manipulators (or flags), it is possible to change the precision and format with which floating point numbers are displayed. There are several formatting options that combine in somewhat complex ways, so we will take a closer look at this.

Group Flag Meaning
floatfield fixed Uses decimal notation for floating-point numbers
floatfield scientific Uses scientific notation for floating-point numbers
floatfield (none) Uses fixed for numbers with few digits, scientific otherwise
floatfield showpoint Always show a decimal point and trailing 0’s for floating-point values

Manipulator Meaning
fixed Use decimal notation for values
scientific Use scientific notation for values
showpoint Show a decimal point and trailing 0’s for floating-point values
noshowpoint Don’t show a decimal point and trailing 0’s for floating-point values
setprecision(int) Sets the precision of floating-point numbers (defined in iomanip.h)

Member function Meaning
precision() Returns the current precision of floating-point numbers
precision(int) Sets the precision of floating-point numbers and returns old precision

If fixed or scientific notation is used, precision determines how many decimal places in the fraction is displayed. Note that if the precision is less than the number of significant digits, the number will be rounded.

Produces the result:

123.456
123.4560
123.45600
123.456000
123.4560000

1.235e+002
1.2346e+002
1.23456e+002
1.234560e+002
1.2345600e+002

If neither fixed nor scientific are being used, precision determines how many significant digits should be displayed. Again, if the precision is less than the number of significant digits, the number will be rounded.

Produces the following result:

123
123.5
123.46
123.456
123.456

Using the showpoint manipulator or flag, you can make the stream write a decimal point and trailing zeros.

Produces the following result:

123.
123.5
123.46
123.456
123.4560

Here’s a summary table with some more examples:

Option Precision 12345.0 0.12345
Normal 3 1.23e+004 0.123
4 1.235e+004 0.1235
5 12345 0.12345
6 12345 0.12345
Showpoint 3 1.23e+004 0.123
4 1.235e+004 0.1235
5 12345. 0.12345
6 12345.0 0.123450
Fixed 3 12345.000 0.123
4 12345.0000 0.1235
5 12345.00000 0.12345
6 12345.000000 0.123450
Scientific 3 1.235e+004 1.235e-001
4 1.2345e+004 1.2345e-001
5 1.23450e+004 1.23450e-001
6 1.234500e+004 1.234500e-001

Width, fill characters, and justification

Typically when you print numbers, the numbers are printed without any regard to the space around them. However, it is possible to left or right justify the printing of numbers. In order to do this, we have to first define a field width, which defines the number of output spaces a value will have. If the actual number printed is smaller than the field width, it will be left or right justified (as specified). If the actual number is larger than the field width, it will not be truncated -- it will overflow the field.

Group Flag Meaning
adjustfield internal Left-justifies the sign of the number, and right-justifies the value
adjustfield left Left-justifies the sign and value
adjustfield right Right-justifies the sign and value (default)

Manipulator Meaning
internal Left-justifies the sign of the number, and right-justifies the value
left Left-justifies the sign and value
right Right-justifies the sign and value
setfill(char) Sets the parameter as the fill character (defined in iomanip.h)
setw(int) Sets the field width for input and output to the parameter (defined in iomanip.h)

Member function Meaning
fill() Returns the current fill character
fill(char) Sets the fill character and returns the old fill character
width() Returns the current field width
width(int) Sets the current field width and returns old field width

In order to use any of these formatters, we first have to set a field width. This can be done via the width(int) member function, or the setw() manipulator. Note that right justification is the default.

This produces the result:

-12345
    -12345
-12345
    -12345
-    12345

One thing to note is that setw() and width() only affect the next output statement. They are not persistent like some other flags/manipulators.

Now, let’s set a fill character and do the same example:

This produces the output:

-12345
****-12345
-12345****
****-12345
-****12345

Note that all the blank spaces in the field have been filled up with the fill character.

The ostream class and iostream library contain other output functions, flags, and manipulators that may be useful, depending on what you need to do. As with the istream class, those topics are really more suited for a tutorial or book focusing on the standard library (such as the excellent book “The C++ Standard Template Library” by Nicolai M. Josuttis).

18.4 -- Stream classes for strings
Index
18.2 -- Input with istream

19 comments to 18.3 — Output with ostream and ios

  • Hi Alex,

    It seems to me that the outputting of numbers with iostream is the worst part of C++ (and it’s not even part of C++!) The thing that really bugs me is the persistance of things like floatfield and the non-persistance of the width settings. It means that for any given output statement you’ve no idea what will be displayed unless you explicitly set everything. For example, setting output to scientific somewhere in your program means that all subsequent output will be scientific unless you explicitly say otherwise - the only way I can see to get back to the default output is to use

    std::cout.unsetf(std::ios::scientific|std::ios::showpoint|std::ios::fixed);

    Bring on C# (or use stdio) I say.

    Anyway enough of that, there are a few typos on this page:

    In the description of the floatfield group, “floatfield” is missing for showpoint.
    In the floating point output examples table, for “fixed” precision 3 there are two decimal points, and for “scientific” precisions 4-6 there are no decimal points.

    VS 2005 seems to have a bug regarding showpoint manipulator. The following code:

    double x = 1.2345;
    cout << showpoint << x << endl;
    cout << scientific << x << endl;
    cout << showpoint << x << endl;
    cout.setf(std::ios::showpoint,std::ios::floatfield);
    cout << x << endl;

    produces:

    1.23450
    1.234500e+000
    1.234500e+000
    1.23450

    so you need to use setf to switch from scientific to showpoint (not that I can imagine that will worry too many people!)

    • I am personally not a fan of the C++ I/O operators for outputting formatted numbers. In those cases, I usually fall back to the old C-style stdio printf() function way of doing things. Thanks for noting the errors.

  • Hugh

    So, how do you go about adjusting the size of the exponent from 3 digits to 2? I have a floating point number that I want outputted as 0.000E+00 instead of 0.000E+000.

    Any ideas?

    Thanks

  • Vinny

    Excellent Site. I am setting a book mark. I tried your examples and everything works fine. I would also like to reset the floating point precision back to its default. I am writing a library routine. I don’t know what the user will have for their default precision but it would be great to capture it, change the precision to my own, then reset it back.
    Thanks,
    Vinny

  • cpp-learner

    Looking forward to see sections on vector, map, iterators, etc… There are many available sources online but I know when Alex write it it will be the best

  • Emiel

    Great tutorials. I’ve read them all so far.

    However, at the boolalpha example on this page I noticed 0 represents true and 1 represents false?

    0 1 -> should be 1 0
    true false
    0 1 -> should be 1 0
    true false

    I ran the example code to be sure (my world would collapse if true was 0 :P).

  • exactly it should be like:

    0 1 –> should be 1 0
    true false
    0 1 –> should be 1 0
    true false

    Excellent Tutorial………….

  • LW

    Hi Alex,
    I think the uppercase examples are not correct. They are actually examples for setprecisions

    • Alex

      No, it’s correct. Using the uppercase manipulator makes std::cout print an uppercase E for the exponent of floating point numbers, as well as uppercase letters when printing hexadecimal values.

  • Devashish

    “uppercase - Uses upper case letters”

    Who uses uppercase letters when this flag/manipulator is applied on streams. The program itself ?

    • Alex

      std::cout does. When the program sends the uppercase manipulator to std::cout, std::cout will print upper case letters for the floating point exponent or hexadecimal values instead of lower case ones.

  • jonas

    Hi Alex,
    I think you made a mistake here by assigning showpoint flag to the floatfield group, since i,ve found  (http://www.cplusplus.com/reference/ios/ios_base/setf/) that it belongs to the so called independent format flags. That’s i think why this code doesn’t perform properly:
    #include <iostream>
    #include <iomanip>
    using namespace std;
    int main ()
    {

    cout.setf(ios_base::showpoint,ios::floatfield);        
    cout << setprecision(4) <<  831.0 << ‘ ‘ << 8e4;

    }
      It prints:831 8e+04. But as soon as I remove ios::floatfield from parameter list it performs as intended:831.0 8.000e+04 .

  • Darren

    For fun I had a go at writing a function that can format a double type to a specified number of significant figures returning the value as a string. It can display numbers in scientific format if that number is either less than some predefined value or greater than some other predefined value. Also you can set a "threshold-to-zero" value such that if the number is less than or equal to this threshold the string representation of the number is set to zero.
    FormatOutput.h

    FormatOutput.cpp

    Note that should a rounded value overflow to the next decimal unit an extra significant figure is given. For example, using this function to round 999.95 to 4 s.f. results in a string containing "1000.0", whereas 999.94 results in the string "999.9", and 1000.04 gives "1000".

  • Kattencrack Kledge

    In the section "Usefull Formaters", the "Group" column is empty on each flag table that has only one row. Is it normal?

  • Matt

    Under "Useful formatters", second sentence, you wrote:
    " manipulators lives in the std namespace".
    I think "lives" should be singular.

Leave a Comment

Put C++ code inside [code][/code] tags to use the syntax highlighter