tags:

views:

135

answers:

4

Why do I get extra digits after the string of Hex digits when using printf?

cout << printf("%06X ", 0xABCDEF);

produces: ABCDEF 7

So where does the 7 come from and how can I get rid of it?

+5  A: 

You're passing the result of the printf operation to cout.

Generally speaking, you use either printf or cout.

printf("%06X",0xABCDEF); //will do what you want in a C-like way

and

std::cout << std::hex << 0xABCDEF; //is the C++ iostream way
jkerian
+1 for qualifying `cout` and `hex`.
Billy ONeal
+9  A: 

You need to use either cout or printf, not both.

printf("%06X ", 0xABCDEF);

Or

cout << hex << 0xABCDEF;

When you do both, the cout prints the result of the printf function, which is the number of characters printed (six characters and a space).

Tmdean
+4  A: 

Try

cout << hex << 0xABCDEF;

The '7' is the return value of the printf() function. It is printed by cout, where the hex string is printed by the printf().

drhirsch
You should probably qualify those with namespace `std`.
Billy ONeal
+3  A: 

printf doesn't work together with cout. printf formats your value and prints it, it doesn't return the formatted value.

The 7 comes from the fact that printf returned that value, which is the total number of characters written. This 7 is then sent to cout, which prints it.

If you want to print formatted text using cout, the simplest way is to use Boost.Format, but the iostreams library also provides functionality for this via manipulators.

Michael Madsen