6

We have %x in C to print any decimal value as hex value like this

printf("%x",a); // here a is having some integral value 

Similarly, can we print this directly in C++ without any much extra effort or without addition of extra header file like <iomanip>?

3
  • 3
    What is wrong with <iomanip>? For printf, you need to #include <stdio.h> and for cout << hex << ... you need to include iomanip ... Otherwise you could just stay with printf() even in C++ Commented Oct 19, 2012 at 9:36
  • Just to correct myself: the correct header file for hex is <iostream>, not <iomanip>. Commented Oct 19, 2012 at 9:50
  • Yeah Thanks , its working ,Previously i was doing std::hex(a) that's why it was asking for iomanip Commented Oct 19, 2012 at 9:54

3 Answers 3

8
#include <iostream> std::cout << std::hex << a; 

You need <iostream> for C++ style output anyway, so it's not an "extra" header.

Sign up to request clarification or add additional context in comments.

11 Comments

Does this not require <iomanip> inclusion? I think this is what the OP for some reason did not want ...
AFAIK, it's part of <iostream>. At least, I can't remember ever including <iomanip>.
Right - anyways, the OP said "... extra header files like <iomanip>" so I assume he also means <iostream> :)
Tested, you don't need anything besides <iostream> (which you need for cout anyway.)
@DevSolar true but you don't need cout (the alternative is <cstdio>)
|
3

printf is available in C++ as well, so you can use the same technique.

(I'm not recommending std::cout or std::hex because you said you don't want that include)

6 Comments

Either you have to include <cstdio> for printf() or <iostream> for std::cout, so the difference doesn't matter. Type safety and overloaded operator<<() does matter, so personally I would never recommend using printf() in a C++ context.
"so the difference doesn't matter" - that depends on the exact requirement. He said he doesn't want headers like <iomanip> which sounds like he doesn't want std headers. Without any includes at all, you can't print anything.
So what makes <cstdio> less of a std header? Besides, he also wrote "can we print this directly in C++", which I took as meaning "using iostream".
yeah i mean to include only one header that is <iostream> and dont want to include any extra headers..
@Omkant then DevSolar's answer should do it. Also, "i mean to include only one header that is <iostream>" is completely different than "without addition of extra header file like <iomanip>"!!!!!!!!!
|
-4

cout << (void *)a << endl;

2 Comments

I think you have a typo or two in your suggestion.
oups, sorry. Anyway, I was not aware of the std::hex which is more proper.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.