Search code examples
c++g++iostreamiomanip

std::ostream ignores hex flag set on the underlying via setf()


The following C++ code surprisingly produces decimal output, apparently ignoring the call to setf() and printing true 42. Using std::setiosflags() Gives the same result. However using std::cout << std::hex does give the expected output true 0x2a, hence std::ios::showbase and std::ios::boolalpha are being honored.

I've tested both G++ 5.4 on Ubuntu and G++ 7.2.1 on CentOS. What am I missing here?

#include <sstream>
#include <iostream>
#include <iomanip> 
#include <iterator>

int main()
{

    std::cout.setf(std::ios::hex | std::ios::showbase | std::ios::boolalpha);
    // Uncommenting the line below doesn't make a difference.
    //std::cout << std::setiosflags(std::ios::hex | std::ios::showbase | std::ios::boolalpha);
    // Uncommenting this line does give the desired hex output.
    //std::cout << std::hex;

    int m = 42;
    std::cout << true << ' ' << m << std::endl;
    return 0;
}

Solution

  • This variant of setf only adds flags, but you need to clear the base field.

    So you need to use the overload with a mask:

        std::cout.setf(std::ios::hex | std::ios::showbase | std::ios::boolalpha,
                       std::ios_base::basefield | std::ios::showbase | std::ios::boolalpha);
    

    Outputs:

    true 0x2a

    Live Demo