0

Consider the following code:

extern "C" {
    #include <lib.h>
}

#include <iostream>

int main() {

    unsigned char a='a';
    unsigned char b=some_struct_in_libh->unsignedchar;

    cout << a << " " << b << endl; //Prints only a

    printf("%u\n",b); //Prints b

    cout << static_cast<int>(b) << endl; //Also prints b

    return 0;
}

Why does it behave like this?

gcandal
  • 937
  • 8
  • 23
  • Since we neither know what `some_struct_in_libh` and what `unsignedchar` and all of their values are, we can only guess that it prints something, but you can not see it. – PlasmaHH Jul 12 '13 at 15:36
  • b is printed as what? Is it a valid character? Do you want it to be treated as a character (a string of one character) or as a number? – Antonio Jul 12 '13 at 15:37

1 Answers1

6

It's not printing only a at all. What you're seeing is instead that cout prints character type data as characters not as numbers. Your b is some character that's non-printable so cout is helpfully printing it as a blank space.

You found the solution by casting it to int.

EDIT: I'm pretty sure your printf is only working by chance because you told it to expect an unsigned int and gave it a character (different number of bytes).

Mark B
  • 95,107
  • 10
  • 109
  • 188
  • 3
    printf works because in the case of a variable argument function, all types of "integral type" are converted to "int" unless they are larger. So the code is perfectly fine as is - but of course, it prints the unsigned value of the char, not the character itself which is correctly addressed in this answer. – Mats Petersson Jul 12 '13 at 15:42
  • Upvote for describing that cout prints character type data as _characters_, converting non-printable input to blanks. `printf("%c", b);` would likely display the garbage character. – Aaron Burke Jul 12 '13 at 18:34
  • The thing here was I was using an external library which created some classes with char as members, but instead of writing the ASCII to it, it wrote as if it was a 1-byte-int, if that makes sense. Anyway, thanks for the help understanding printing. – gcandal Jul 15 '13 at 16:36