Search code examples
c++iomanip

How do I properly set ios flags for stream manipulation?


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?


Solution

  • To set hex you need to clear all the basefields. 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);