• Home
  • 2.8 Formatting Integers

2.8 Formatting Integers

View Categories

2.8 Formatting Integers

1 min read

Table of Contents

C++ provides stream manipulators that control how integer values are displayed. By default, integers are printed in decimal format. The Standard Library also allows integers to be displayed in hexadecimal and octal formats using stream manipulators.

These manipulators change the formatting of subsequent integer output until another formatting manipulator is applied.

Source Code #

#include <iostream>
#include <iomanip>

int main()
{
    int number = 255;

    std::cout << "Decimal     : " << std::dec << number << '\n';
    std::cout << "Hexadecimal : " << std::hex << number << '\n';
    std::cout << "Octal       : " << std::oct << number << '\n';

    return 0;
}

Output #

Decimal     : 255
Hexadecimal : ff
Octal       : 377

Explanation #

  • #include <iomanip> includes the header that provides stream manipulators for formatting input and output.
  • std::dec formats integer values in decimal (base 10).
  • std::hex formats integer values in hexadecimal (base 16).
  • std::oct formats integer values in octal (base 8).
  • These manipulators affect how subsequent integer values are displayed until another base manipulator is used.
  • The stored value of the variable does not change; only its representation in the output stream changes.
  • std::cout displays the formatted integer values on the console.
  • return 0; terminates the program successfully.

Powered by BetterDocs

Leave a Reply

Your email address will not be published. Required fields are marked *