Reputation: 2758
I typed up a basic example in C++ in which I try to print a number to screen as hexadecimal below:
#include <iostream>
#include <iomanip>
int main()
{
unsigned number {314};
auto flags {std::ios::showbase | std::ios::hex};
std::cout.setf(flags);
// expected output: 0x13A
std::cout << number << std::endl;
std::cout.unsetf(flags);
// expected output: 314
std::cout << number << std::endl;
return 0;
}
However, the number is never displayed in hexadecimal format. Am I setting the flags properly?
Upvotes: 3
Views: 846
Reputation: 141200
To set hex
you need to clear all the basefield
s. If you don't do it, then both the hex
and dec
flags are both set. While I am not sure what should happen if multiple flags for the same mask are set, your implementation chooses to use dec
, when both hex
and dec
flags are set.
You want:
std::cout.setf(std::ios::hex, std::ios::basefield);
std::cout.setf(std::ios::showbase);
and then clear with
std::cout.setf(std::ios::dec, std::ios::basefield);
std::cout.unsetf(std::ios::showbase);
Upvotes: 5