tags:

views:

115

answers:

3

i am a c coder, new to c++.

i try to print the following with cout with strange output. Any comment on this behaviour is appreciated.

#include<iostream>
using namespace std;

int main()
{
        unsigned char x = 0xff;

        cout << "Value of x  " << hex<<x<<"  hexadecimal"<<endl;

        printf(" Value of x %x by printf", x);
}

output:

 Value of x  ÿ  hexadecimal
 Value of x ff by printf
+5  A: 

<< handles char as a 'character' that you want to output, and just outputs that byte exactly. The hex only applies to integer-like types, so the following will do what you expect:

cout << "Value of x  " << hex << int(x) << "  hexadecimal" << endl;

Billy ONeal's suggestion of static_cast would look like this:

cout << "Value of x  " << hex << static_cast<int>(x) << "  hexadecimal" << endl;
Thanatos
+1 -- but you should be using `static_cast` here.
Billy ONeal
so the "<<hex " is not equivalent to printf ("%x", x), where, the bit stream at that location is treated as a hex value ?Thanks a lot for the responses..it is very helpful
@pdk: It is meant to be the equivalent, but it only has an effect when `cout << x` would normally output some decimal representation. Since `cout << (a char)` doesn't (it outputs that byte directly), the `hex` makes no sense, and is not applied. Thus, we force a conversion to an `int` type, and the `<<` that deals with `int` is called, which outputs a hex representation.
Thanatos
Ok thanks a lot for the comments, were really helpful.So to summarise, as far as i understood, the unsigned char overload happens in this case. And << hex is ignored, resulting output in char format.
+1  A: 

You are doing the hex part correctly, but x is a character, and C++ is trying to print it as a character. You have to cast it to an integer.

#include<iostream>
using namespace std;

int main()
{
        unsigned char x = 0xff;

        cout << "Value of x  " << hex<<static_cast<int>(x)<<"  hexadecimal"<<endl;

        printf(" Value of x %x by printf", x);
}
Starkey
Thanks a lot Starkey.Then why printf , prints the hex value of the character correctly ? I am sorry for this basic q ...
In printf by specifying %x you are telling C++ how to interpret x, whereas with hex << x the compiler will use the unsigned char overload of the streaming operator since this is the type. By changing the type of x to int, the int overload of << will apply.
nonnb
God C++ is ugly /shdder
cletus
@cletus: C++ has printf, too. That being said, the two functions have completely different strategies. I find `cout` more intuitive for everyday use, but it tends to become painful compared to `printf` once you want fancy formatting of output.
Brian
A: 

also, iostreams can be a pain with their 'manipulators'. To do anything interesting for human readable output, you might want to look at boost::format, which brings all the joys of printf to the world of typesafe output.

bert hubert