Search code examples
c++iomanip

Using hex flag inside setiosflags function


int a=60;
cout<<setiosflags(ios::hex|ios::showbase|ios::uppercase);
cout<<a<<endl;

The above code is not working but if I use

cout<<hex

and then

cout<<setiosflags(ios::showbase|ios::uppercase)

then it is working

Why? and how i do know which one can be used inside setiosflags() ?


Solution

  • You need to call resetiosflags before you call setiosflags. The reason for this is that setiosflags(ios::hex|ios::showbase|ios::uppercase) just appends these flags into the stream as if calling setf and that gives conflicting flags in the stream. Using

    std::cout << std::resetiosflags(std::ios_base::dec)
              << std::setiosflags(std::ios::hex|std::ios::showbase|std::ios::uppercase)
              << a << endl;
    

    will make it display a correctly.