문제

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?

도움이 되었습니까?

해결책

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).

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top