C++ ios::Showbase() Function



The C++ std::ios::showbase() function is a stream manipulator that enables the display of numerical base prefixes when outputting integer values. When this function is activated, it ensures that hexadecimal numbers are prefixed with 0x, octal numbers with 0, and decimal numbers are unaffected.

Syntax

Following is the syntax for std::ios::showbase() function.

ios_base& showbase( std::ios_base& str );

Parameters

  • str − It indicates the stream object whose format flag is affected.

Return Value

This function returns the Argument str.

Exceptions

If an exception is thrown, str is in a valid state.

Data races

It modifies str. Concurrent access to the same stream object may cause data races.

Example

Let's look at the following example, where we are going to use the showbase() function with decimal.

#include 
#include 
int main()
{
    int x = 112;
    std::cout << "Decimal default : " << x << std::endl;
    std::cout << std::showbase;
    std::cout << "Decimal With showbase : " << x << std::endl;
    return 0;
}

Output

Output of the above code is as follows −

Decimal default : 112
Decimal With showbase : 112

Example

Consider the following example, where we are going to use the showbase() function with hexadecimal.

#include 
#include 
int main()
{
    int x = 234;
    std::cout << std::hex;
    std::cout << "Hexadecimal default : " << x << std::endl;
    std::cout << std::showbase;
    std::cout << "Hexadecimal With showbase : " << x << std::endl;
    return 0;
}

Output

Following is the output of the above code −

Hexadecimal default : ea
Hexadecimal With showbase : 0xea

Example

In the following example, we are going to use the showbase() function with the octal.

#include 
#include 
int main()
{
    int x = 1123;
    std::cout << std::oct;
    std::cout << "Octal default : " << x << std::endl;
    std::cout << std::showbase;
    std::cout << "Octal With showbase : " << x << std::endl;
    return 0;
}

Output

If we run the above code it will generate the following output −

Octal default : 2143
Octal With showbase : 02143
ios.htm
Advertisements