Home > Mobile >  C : scanf or wscanf, I can't print correctly the accented character
C : scanf or wscanf, I can't print correctly the accented character

Time:02-24

I'm trying to printf a character/String given by the user with accents, but this doesn't work. After consulting a lot of forums, I think that <wchar.h> can solve my problem, but I have the same result.

main() {
    setlocale(LC_ALL, "");

    char buffer[50], choix;

    printf("CHAR\nEntrez un char : ");
    scanf(" %c", &choix);
    printf("%c\n", choix);
    getchar();

    printf("Entrez votre éùàç prénom : ");
    scanf("%s", buffer);
    getchar();
    printf("%s\n\n", buffer);

    wchar_t wbuffer[50], wchoix;

    printf("WCHAR\nEntrez un char : ");
    wscanf(L" %lc", &wchoix);
    wprintf(L"%lc\n", wchoix);
    getchar();

    wprintf(L"Entrez votre éùàç prénom : ");
    wscanf(L"%ls", wbuffer);
    getchar();
    wprintf(L"%ls\n\n", wbuffer);
    
    _getch();
}

The result was (on Windows 10 or Windows 11): result in cmd

If I see the CP850/CP1252 table : -126 = 130 -> é / '
10 -> LF ( \n )

in wchar, if it's Unicode 0x201a -> ' (é it's 0x00E9)

Then I receive from stdin a CP850 code and printf a CP1252 one.... There's no other solution to solve this except the SetConsoleCP/SetConsoleOutputCP from windows.h (or system("CHCP 1252))? The setlocale don't change the 'stdin' from CP850 (default win consol) to CP1252?

At the end, I will do it all in English, it's more simple. ;)


I try another thing that's seem to confirm that the setlocal don't modify the console :

cmd chcp

Same result with "setlocale(LC_ALL, ".1252");". The SetConsole seem to be unavoidable :/

CodePudding user response:

In final, the better compromise I found : portable code

Using narrow or wide, this is the only way that's work.

thanks to all for the help in the reflexion ;)

  • Related