Home  >  Article  >  Backend Development  >  How to input Chinese characters in c++

How to input Chinese characters in c++

下次还敢
下次还敢Original
2024-05-09 04:12:20367browse

There are three ways to input Chinese characters in C: use the std::wcin stream, which is specially used to input multi-byte characters. Use cin.imbue() to associate the stream to a specific locale, such as zh_CN.UTF-8. Convert non-UTF-8 encoded Chinese characters to wide characters using a custom conversion function.

How to input Chinese characters in c++

How to input Chinese characters in C

Introduction:
In C Inputting Chinese characters requires processing multi-byte character encoding. This article will explore common methods, including using std::wcin, cin.imbue(), and custom conversion functions.

Using std::wcin:
The std::wcin stream is used to input wide characters, that is, multi-byte characters. It can receive UTF-16 or UTF-32 encoded Chinese characters.

<code class="cpp">#include <iostream>

int main() {
  wchar_t ch;
  std::wcin >> ch;
  std::cout << ch << std::endl;
  return 0;
}</code>

Using cin.imbue(): The
cin.imbue() function can associate a stream to a specific locale that specifies the character encoding. For Chinese character input, you can use zh_CN.UTF-8 or other locales that support UTF-8 encoding.

<code class="cpp">#include <iostream>
#include <locale>

int main() {
  std::cin.imbue(std::locale("zh_CN.UTF-8"));
  char ch;
  std::cin >> ch;
  std::cout << ch << std::endl;
  return 0;
}</code>

Use a custom conversion function:
For non-UTF-8 encoded Chinese characters, you can use a custom conversion function to convert multi-byte characters to wide characters. Take GB2312 encoding as an example:

<code class="cpp">#include <iostream>
#include <codecvt>

std::wstring gb2312_to_wstring(const char* gb2312) {
  std::codecvt_utf8<wchar_t> cvt;
  std::wstring_convert<std::codecvt_utf8<wchar_t>> conv;
  return conv.from_bytes(gb2312);
}

int main() {
  char gb2312[] = "你好";
  std::wstring wstr = gb2312_to_wstring(gb2312);
  std::wcout << wstr << std::endl;
  return 0;
}</code>

The above is the detailed content of How to input Chinese characters in c++. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:Usage of class in c++Next article:Usage of class in c++