Output Streams

# Temporarily Change Output Base

## Can I change the base of a number output temporarily without affecting subsequent outputs?

Yes, you can temporarily change the base of a number output in C++ without affecting subsequentÂ outputs.

This is useful when you need to display a number in a different base for a specific operation while keeping the rest of the output in the defaultÂ base.

## Using std::dec, std::hex, and std::oct

The manipulators std::dec, std::hex, and std::oct change the base of the output. These changes remain in effect until another base manipulator isÂ used.

Hereâ€™s an example of temporarily changing the base to hexadecimal and then back toÂ decimal:

#include <iostream>

int main() {
int number = 255;

std::cout << "Decimal: " << number << '\n';
<< std::hex << number << '\n';
std::cout << "Back to Decimal: "
<< std::dec << number;
}
Decimal: 255
Back to Decimal: 255

In this example, the base is changed to hexadecimal for the second output and reverted to decimal for the thirdÂ output.

## Combining with Other Manipulators

You can also use base manipulators with other manipulators like std::setw() and std::setfill() to format the output moreÂ precisely:

#include <iostream>
#include <iomanip>

int main() {
int number = 255;

std::cout
<< "Hex: "
<< std::setw(10)
<< std::setfill('0')
<< std::hex << number << '\n';

std::cout
<< "Decimal: "
<< std::dec
<< number;
}
Hex: 00000000ff
Decimal: 255

Here, std::setw(10) and std::setfill('0') are used to pad the hexadecimal number withÂ zeros.

## Function Approach

If you frequently need to switch bases, consider creating functions to encapsulate thisÂ behavior:

#include <iostream>
#include <iomanip>

void printHex(int number) {
std::cout << std::hex << number << std::dec;
}

int main() {
int number = 255;
std::cout << "Decimal: " << number << '\n';
printHex(number);
}
Decimal: 255
Hexadecimal: ff

## Summary

By using manipulators like std::hex, std::dec, and std::oct, you can temporarily change the base of the output without affecting subsequent outputs. This allows for flexible and precise formatting in your C++Â programs.

This Question is from the Lesson:

### Output Streams

A detailed overview of C++ Output Streams, from basics and key functions to error handling and custom types.

Answers to questions are automatically generated and may not have been reviewed.

This Question is from the Lesson:

### Output Streams

A detailed overview of C++ Output Streams, from basics and key functions to error handling and custom types.

Part of the course:

## Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Free, unlimited access

### This course includes:

• 124 Lessons
• 550+ Code Samples
• 96% Positive Reviews
• Regularly Updated
• Help and FAQ
Free, Unlimited Access

### Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.