Home > database >  printf() not working with wchar_t no matter what I try
printf() not working with wchar_t no matter what I try

Time:12-06

This doesn't work - nothing is printed.

#include <stdio.h>
#include <locale.h>
#include <wchar.h>

int main(void) {
    setlocale(LC_ALL,"");
    wchar_t a = 0xfe;
    printf("%lc",a);
    return 0;
}

I've just been staring at it and trying different things for minutes.

int main(void) {
    setlocale(LC_ALL,"");
    wchar_t a = '\u00FE';
    printf("%lc",a);
    return 0;
}
int main(void) {
    setlocale(LC_ALL,"");
    wchar_t a = '\U000000FE';
    printf("%lc",a);
    return 0;
}
int main(void) {
    setlocale(LC_ALL,"");
    wchar_t a = 0xfe;
    wchar_t* b = &a;
    printf("%ls",b);
    return 0;
}
int main(void) {
    setlocale(LC_ALL,"");
    wchar_t* b = L"\u00FE";
    printf("%ls",b);
    return 0;
}
int main(void) {
    setlocale(LC_ALL,"");
    wchar_t a = 0xfe;
    printf("%C",a);
    return 0;
}

Nothing works. The only thing that works is this, but say I want it in a variable:

printf("\u00FE");

Actually, the tooltip in vscode does show a thorn, but the actual program doesn't.

Environment: Windows 10, VSCode, just the C/C Extension Pack, GCC GNU something MinGW (I think)

CodePudding user response:

The terminal you are printing to expects a stream of bytes which encode the characters that you wish to print. Here's how you could encode your character and print it to a terminal which understands UTF-8:

#include <stdio.h>
#include <locale.h>
int main(void) {
    char a[] = { 0xc3, 0xbe, '\n', 0};
    printf("%s",a);
    return 0;
}

Output is:

þ
  • Related