c++manipulators

How to print out a decimal number as octal number using setiosflags in C++


I have tried this

cout. setf(ios::oct, ios::basefield) ;
cout << 79 << endl;

It works but using manipulator setiosflags

cout << setiosflags (ios::oct) << 79 << endl;

It doesn't work, there's still 79 printed at the screen.
Although I heard setiosflags is the alternative of `setf.

Then how to print out the decimal number as octal number using setiosflags?


Solution

  • You need to reset the flags first using the std::resetiosflags:

    #include <iostream>
    #include <iomanip>
    
    int main()
    {
      int x = 42;
      std::cout << std::resetiosflags(std::ios_base::dec)
                << std::setiosflags(std::ios_base::hex | std::ios_base::showbase)
                << x;
    }
    

    The | std::ios_base::showbase part is optional.