Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problem with printing wide character in c

Hello I want to print the letter 'å' which is 131 in extended ascii and as far as I can see has UTF-8 code 00E5 and 0x00E5 in UTF-16. However, in the code below the program prints 'Õ' which is not what I wanted. I do not know what I have done wrong. Thanks in advance.

int main(void) {

   wchar_t myChar = 0x00E5;

   wprintf(L"%lc", myChar);

}
like image 610
Alexander Jonsson Avatar asked Nov 05 '25 05:11

Alexander Jonsson


2 Answers

I'd try using an UTF-16 character literal and also set the locale (setlocale) to CP_UTF_16LE if using MSVC or to the user-preferred locale if not.

#ifdef _MSC_VER
#include <io.h>     // _setmode
#include <fcntl.h>  // _O_U16TEXT
#endif

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

void set_locale_mode() {
#ifdef _MSC_VER
    // Unicode UTF-16, little endian byte order (BMP of ISO 10646)
    const char *CP_UTF_16LE = ".1200";

    setlocale(LC_ALL, CP_UTF_16LE);
    _setmode(_fileno(stdout), _O_U16TEXT);
#else
    // set the user-preferred locale
    setlocale(LC_ALL, "");
#endif
}

int main(void) {
    set_locale_mode();  // do this before any other output

    // UTF-16 character literal with unicode for `å`:
    wchar_t myChar = u'\u00E5';

    wprintf(L"%lc", myChar);
}

Tested in Windows 11 with VS2022

like image 187
Ted Lyngmo Avatar answered Nov 08 '25 01:11

Ted Lyngmo


On Windows, to output Unicode characters the console mode needs to be changed:

#include<fcntl.h>
#include <io.h>
#include <stdio.h>

int main(void) {
    _setmode(_fileno(stdout), _O_U16TEXT);

    // UTF-16 character literal with unicode for `å`:
    wchar_t myChar = 0x00E5;

    // Adding U+20AC EURO SIGN as well.
    wprintf(L"\u20ac%lc", myChar);
}

Output:

ی
like image 43
Mark Tolonen Avatar answered Nov 08 '25 02:11

Mark Tolonen