Why do cout & fprintf fumble chars?

Viewed 25

Hard to believe. It must be me. Both iostream and fprintf won't print chars?

#include <iostream>

using namespace std;

int main()
{
    cout << "Signed char:" << endl;
    char vv = 5;
    cout << "cout vv = " << vv << endl;
    fprintf( stderr, "C vv %c\n", vv );
    fprintf( stderr, "C vv %d\n", vv );
    fprintf( stderr, "C vv %hhd\n", vv );

    cout << endl << "Negative signed char:" << endl;
    char vn = -6;
    cout << "cout vn = " << vn << endl;
    fprintf( stderr, "C vn %c\n", vn );
    fprintf( stderr, "C vn %d\n", vn );
    fprintf( stderr, "C vn %hhd\n", vn );

    cout << endl << "Unsigned char:" << endl;
    unsigned char vu = 7;
    cout << "cout vu = " << vu << endl;
    fprintf( stderr, "C vu %c\n", vu );
    fprintf( stderr, "C vu %u\n", vu );
    fprintf( stderr, "C vu %hhu\n", vu );
}

OUTPUT:

spinv$ g++ -o test test.cpp
spinv$ ./test 
Signed char:
cout vv = 
C vv 
C vv 5
C vv 5

Negative signed char:
cout vn = �
C vn �
C vn -6
C vn -6

Unsigned char:
cout vu = 
C vu 
C vu 7
C vu 7

I don't get it. I have tested it on these:

spinv$ uname -a
Linux sutro 5.10.0-15-amd64 #1 SMP Debian 5.10.120-1 (2022-06-09) x86_64 GNU/Linux
spinv$ g++ --version
g++ (Debian 10.2.1-6) 10.2.1 20210110

(base) me@toolchain:~$uname -a
Linux toolchain 4.4.0-190-generic #220-Ubuntu SMP Fri Aug 28 23:02:15 UTC 2020 x86_64 x86_64 x86_64 GNU/Linux
(base) me@toolchain:~$g++ --version
g++ (Ubuntu 6.5.0-2ubuntu1~16.04) 6.5.0 20181026

(base) ➜  Downloads uname -a
Darwin TOEJAM.local 20.6.0 Darwin Kernel Version 20.6.0: Tue Jun 21 20:50:28 PDT 2022; root:xnu-7195.141.32~1/RELEASE_X86_64 x86_64
(base) ➜  Downloads g++ --version
Configured with: --prefix=/Library/Developer/CommandLineTools/usr --with-gxx-include-dir=/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/include/c++/4.2.1
Apple clang version 13.0.0 (clang-1300.0.29.30)
Target: x86_64-apple-darwin20.6.0

and all act the exact same. So that means I have a misunderstanding, surely?

THANKS!

The site wouldn't let me post the above because it wants more in the way of explanation, but I cannot think of what more there is to say. Maybe if I just add the code snippet again, or a fave poem or something? OKAY, now it is happy!

0 Answers
Related