13.6.1. Integral Stream Base: dec, oct, hex and setbase

Integers are interpreted normally as decimal (base-10) values. To change the base in which integers are interpreted on a stream, insert the hex manipulator to set the base to hexadecimal (base 16) or insert the oct manipulator to set the base to octal (base 8). Insert the dec manipulator to reset the stream base to decimal. These are all sticky manipulators.

A stream’s base also may be changed by the setbase stream manipulator, which takes an int argument of 10, 8, or 16 to set the base to decimal, octal or hexadecimal, respectively. Because setbase takes an argument, it’s called a parameterized stream manipulator. Parameterized stream manipulators like setbase require the header <iomanip>. The stream base value remains the same until changed explicitly; setbase settings are sticky. Figure 13.8 demonstrates stream manipulators hex, oct, dec and setbase. For more information on decimal, octal and hexadecimal numbers, see Appendix D.


 1   // Fig. 13.8: fig13_08.cpp
 2   // Using stream manipulators hex, oct, dec and setbase.
 3   #include <iostream>
 4   #include <iomanip> 
 5   using namespace std;
 6
 7   int main()
 8   {
 9      int number;
10
11      cout << "Enter a decimal number: ";
12      cin >> number; // input number
13
14      // use hex stream manipulator to show hexadecimal number
15      cout << number << " in hexadecimal is: " << hex
16         << number << endl;
17
18      // use oct stream manipulator to show octal number
19      cout << dec << number << " in octal is: "
20         << oct << number << endl;
21
22      // use setbase stream manipulator to show decimal number
23      cout << setbase( 10 ) << number << " in decimal is: "
24         << number << endl;
25   } // end main


Enter a decimal number: 20
20 in hexadecimal is: 14
20 in octal is: 24
20 in decimal is: 20


Fig. 13.8. Using stream manipulators hex, oct, dec and setbase.

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

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