Frank Vilea
Frank Vilea

Reputation: 8477

C Wide characters - how to use them?

I'm able to output a single character using this code:

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

main(){

setlocale(LC_CTYPE, "");
wchar_t a = L'Ö';
putwchar(a);

}

How can I adapt the code to output a string?

Something like

wchar_t *a = L"ÖÜÄöüä";
wprinf("%ls", a);

Upvotes: 1

Views: 332

Answers (2)

Kerrek SB
Kerrek SB

Reputation: 476990

It's a bit tricky, you have to know what your internal wchar_ts mean. (See here for a little discussion.) Basically you should communicate with the environment via mbstowcs/wcstombs, and with data with known encoding via iconv (converting from and to WCHAR_T).

(The exception here is Windows, where you can't really communicate with the environment meaningfully, but you can access it in a wide version directly with Windows API functions, and you can write wide strings directly into message boxes etc.)

That said, once you have your internal wide string, you can convert it to the environment's multibyte string with wcstombs, or you can just use printf("%ls", mywstr); which performs the conversion for you. Just don't forget to call setlocale(LC_CTYPE, "") at the very beginning of your program.

Upvotes: 0

Dhaivat Pandya
Dhaivat Pandya

Reputation: 6536

wprintf(L"%ls", str)

Upvotes: 2

Related Questions