ChaseTheSun
ChaseTheSun

Reputation: 3840

How can I get and print the nth character of a wchar_t?

given:

wchar_t* str = L"wide chars";

how get i extract one character at a time in c (not c++)?

for example, I tried

for (int i = 0; i < wcslen(str); i++) {
    printf("%wc\n", str[i]);
}

But only gave me gibberish

Upvotes: 0

Views: 1068

Answers (1)

rici
rici

Reputation: 241901

On Linux (Ubuntu), the following worked fine:

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

int main() {
  /* See below */
  setlocale(LC_ALL, "");
  wchar_t* str = L"日本語";
  for (int i = 0; i < wcslen(str); i++) {
        printf("U+%04x: %lc\n", str[i], str[i]);
  }
  return 0;
}

The setlocale call is important. Without it, the program will execute in the C locale, in which there is no wide character to multibyte conversion, which is necessary for the %lc format code. setlocale(LC_ALL, ""); causes the process's locale to be set to the defaults defined by the various environment variables.

Upvotes: 2

Related Questions