S M Tushar Ibne Salam
S M Tushar Ibne Salam

Reputation: 143

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?

Upvotes: 3

Views: 592

Answers (4)

Israr Ahmad
Israr Ahmad

Reputation: 1

Just try this your issue will be resolve. cout << hex << 79; cout << oct << 79;

Upvotes: 0

Ron
Ron

Reputation: 15511

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.

Upvotes: 4

Yksisarvinen
Yksisarvinen

Reputation: 22219

Keep It Simple and Stupid (or shortly KISS):

std::cout << std::oct << 79 << std::endl;

std::oct is a syntactic sugar for str.setf(std::ios_base::oct, std::ios_base::basefield), which (as you noticed) is one of the ways to force stream to print integral values in octal notation.

See it online

Upvotes: 6

fanta
fanta

Reputation: 21

you can use also

 printf("%o",79);

Upvotes: 0

Related Questions