4

I'm trying to assign the Chinese character 牛 as a char value in C++. On Xcode, I get the error:

"Character too large for enclosing character literal type."

When I use an online IDE like JDoodle or Browxy, I get the error:

"multi-character character constant."

It doesn't matter whether I use char, char16_t, char32_t or wchar_t, it won't work. I thought any Chinese character could at least fit into wchar_t, but this appears not to be the case. What can I do differently?

char letter = '牛';
char16_t character = '牛';
char32_t hanzi = '牛';
wchar_t word = '牛';
Cœur
  • 37,241
  • 25
  • 195
  • 267
K Man
  • 602
  • 2
  • 9
  • 21
  • What encoding? If you don't know the encoding you are working, it will be difficult to make any recommendations. C++ certainly has deficiencies regarding encodings. For example, Unicode UTF-8 a `char` type is not a _character_, rather it is a Unicode UTF-8 encoding unit, of which one-or-more of them are needed to express a single Unicode code point. And it may take several Unicode code points to represent a single character. – Eljay May 09 '20 at 00:36

1 Answers1

13

All of your character literals are standard chars. To get a wider type, you need to include the proper prefix on the literal:

char letter = '牛';
char16_t character = u'牛';
char32_t hanzi = U'牛';
wchar_t word = L'牛';
1201ProgramAlarm
  • 32,384
  • 7
  • 42
  • 56
  • 5
    Just note that there is no character encoding where `'牛'` (U+725B) will ever fit in a single `char`, so `char letter = '牛';` will never work. `char letter[] = "牛";` *may* work, depending on the encoding of the source file. Better would be `char letter[] = u8"牛";` for UTF-8 (or `char8_t` in C++20) – Remy Lebeau May 09 '20 at 00:51