13.7.4. Integral Stream Base (dec, oct, hex, showbase)

C++ provides stream manipulators dec, hex and oct to specify that integers are to be displayed as decimal, hexadecimal and octal values, respectively. Stream insertions default to decimal if none of these manipulators is used. With stream extraction, integers prefixed with 0 (zero) are treated as octal values, integers prefixed with 0x or 0X are treated as hexadecimal values, and all other integers are treated as decimal values. Once a particular base is specified for a stream, all integers on that stream are processed using that base until a different base is specified or until the program terminates.

Stream manipulator showbase forces the base of an integral value to be output. Decimal numbers are output by default, octal numbers are output with a leading 0, and hexadecimal numbers are output with either a leading 0x or a leading 0X (as we discuss in Section 13.7.6, stream manipulator uppercase determines which option is chosen). Figure 13.17 demonstrates the use of stream manipulator showbase to force an integer to print in decimal, octal and hexadecimal formats. To reset the showbase setting, output the stream manipulator noshowbase.


 1   // Fig. 13.17: fig13_17.cpp
 2   // Stream manipulator showbase.
 3   #include <iostream>
 4   using namespace std;
 5
 6   int main()
 7   {
 8      int x = 100;
 9
10      // use showbase to show number base
11      cout << "Printing integers preceded by their base:" << endl
12         << showbase;
13
14      cout << x << endl; // print decimal value
15      cout << oct << x << endl; // print octal value
16      cout << hex << x << endl; // print hexadecimal value
17   } // end main


Printing integers preceded by their base:
100
0144
0x64


Fig. 13.17. Stream manipulator showbase.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.189.171.52