简体   繁体   中英

Why does cout not print extern “C” variable?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM