Home > Article > Backend Development > How to input Chinese characters in c++
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
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!