Conversion Routines

So far we have just considered writing characters and strings. In this section, we consider some of the more sophisticated I/O operations: conversions.

To write a number to a printer or terminal, you must convert the number to characters. The printer understands only characters, not numbers. For example, the number 567 must be converted to the three characters "5", "6", and "7" to be printed.

The << operator is used to convert data to characters and put them in a file. This function is extremely flexible. It can convert a simple integer into a fixed- or variable-size string as a hex, octal, or decimal number with left or right justification. So far you've been using the default conversion for your output. It serves pretty well, but if you want to control your output exactly, you need to learn about conversion flags.

The member functions setf and unsetf are used to set and clear the flags that control the conversion process. The general form of the functions is:

file_var.setf(flags);   // Set flags
file_var.unsetf(flags); // Clear flags

Table 16-3 lists the various flags and their meanings.

Table 16-3: I/O conversion flags




Skip leading whitespace characters on input.


Output is left justified.


Output is right justified.


Numeric output is padded by inserting a fill character between the sign or base character and the number itself.


Use the character version of true and false ("true", "false") for input and output.


Output numbers in base 10, decimal format.


Output numbers in base 8, octal format.


Output numbers in base 16, hexadecimal format.


Print out a base indicator at the beginning of each number. For example, hexadecimal numbers are preceded with "0x".


Show a decimal point for all floating-point numbers whether or not it's needed.


When converting hexadecimal numbers, show the digits A-F as uppercase.


Put a plus sign before all positive numbers.


Convert all floating-point numbers to scientific notation on output.


Convert all floating-point numbers to fixed point on output.


Buffer output. (More on this later.)

If you want to output a number in hexadecimal format, all you have to do is this:

number = 0x3FF;
std::cout << "Dec: " << number << '\n';
std::cout << "Hex: " << number << '\n';

When run, this program produces the output:

Dec: 1023
Hex: 3ff

TIP: People normally expect the output mode to be decimal, so it is a good idea to reset the mode after each output to avoid later confusion.

When converting numbers to characters, the member function:

int file_var.width(int size);

determines the minimum characters to use. For example, the number 3 would normally convert to the character string "3" (note the lack of spaces). If the width is set to four, the result would be "3" where represents a single space.

The member function:

int file_var.precision(int digits);

controls how many digits are printed after the decimal point.

Finally, the function:

char file_var.fill(char pad);

determines the fill character. This character is used for padding when a number is smaller than the specified width.

TIP:  Some of these flags and parameters are reset after each output call and some are not. Which flags are permanent and which are temporary seems to change from compiler to compiler. In general, don't assume anything is going to remain set and you'll be okay. (Just because you're paranoid doesn't mean the compiler isn't out to get you.)

These functions can be called directly, or you can use an I/O manipulator. An I/O manipulator is a special function that can be used in an I/O statement to change the formatting. You can think of a manipulator as a magic bullet that, when sent through an input or output file, changes the state of the file. A manipulator doesn't cause any output; it just changes the state. For example, the manipulator hex changes the output conversion to hexadecimal.

#include <iostream>
number = 0x3FF;
std::cout << "Number is " << std::hex << number << std::dec << '\n';

The header file <iostream> defines a basic set of manipulators. Table 16-4 contains a list of these manipulators.

Table 16-4: I/O manipulators




Output numbers in decimal format.


Output numbers in hexadecimal format.


Output numbers in octal format.


Skip whitespace on input.


Output end-of-line


Output end-of-string (`\0').


Force any buffered output out. (See Chapter 17, for an explanation of how to use this function).

The more advanced set of manipulators (see Table 16-5) is defined in the header file <iomanip>.

Table 16-5: I/O manipulators



std::setiosflags(long flags)

Set selected conversion flags.

std::resetiosflags(long flags)

Reset selected flags.

std::setbase(int base)

Set conversion base to 8, 10, or 16. Sort of a generalized std::dec, std::hex, std::oct.

std::setw(int width)

Set the width of the output.

std::setprecision(int precision)

Set the precision of floating-point output.

std::setfill(char ch)

Set the fill character.

Example 16-3 shows how some of the I/O manipulators may be used.

Example 16-3: io/io.cpp

#include <iostream>
#include <iomanip>
int main(  )
    int number = 12;    // A number to output
    float real = 12.34; // A real number
    std::cout << "123456789012345678901234567890\n"; // output ruler
    std::cout << number << "<-\n";
    std::cout << std::setw(5) << number << "<-\n";
    std::cout << std::setw(5) << std::setfill('*') << 
        number << "<-\n";
    std::cout << std::setiosflags(std::ios::showpos|std::ios::left) << 
        std::setw(5) << number << "<-\n";
    std::cout << real << "<-\n";
    std::cout << std::setprecision(1) << 
        std::setiosflags(std::ios::fixed) << real << "<-\n";
    std::cout << std::setiosflags(std::ios::scientific) << real << "<-\n";
    return (0);

The output of this program is:


Page:  1   2   3   4   5   6   7   8   9   Next 


  • There are no comments yet. Be the first to comment!

Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • On-Demand Oracle Webcast As disruption driven by the cloud, mobile and open source accelerates, developers and development organizations are taking a larger role in technology decision-making at the firms they work for. But what choices are are these organizations actually making? Join Forrester Vice President & Principal Analyst Jeffrey Hammond for an examination of the choices developers are making, trends in programming language adoption, adoption of frameworks, and how development projects are moving to …

  • Live Event Date: June 30, 2016 @ 1:00 p.m. ET / 10:00 a.m. PT There's a disconnect happening in our mobile strategies. We have top-down mandate that our organizations should be "mobile first" and undergo "digital transformations" without a lot of additional insight as to how that should become a reality. In the meantime, members within our organizations inherently understand the benefits of mobile apps -- and, understandably, they want to benefit from them. But the resources to bring an app into existence …

Most Popular Programming Stories

More for Developers

RSS Feeds

Thanks for your registration, follow us on our social networks to keep up-to-date