'How can I allow Chinese characters in C++ input?
I've been trying to take Chinese (simplified) inputs through both the iostream in Visual Studio 2019. When I input an English word, it works fine. To make sure that the console is printing correctly, I changed the console font to something compatible with Chinese characters. Printing characters doesn't appear to be much of an issue as of yet, but inputting characters is causing me some trouble.
I tried a couple of 'fixes' found in other posts such as setlocale(LC_ALL, "zh_CN.UTF-8") or wcin.imbue(locale("zh_CN.UTF-8")) or SetConsoleCP(UTF8), and variants of those functions. While trying to debug, I found that the value of b = L""; the characters that I typed in were completely ignored.
However, when I read input from the file, it appears to be functioning; I can parse, manipulate, and print files properly.
void prepare() {
HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
// Change font to something compatible with chinese
CONSOLE_FONT_INFOEX fontInfo;
fontInfo.cbSize = sizeof(fontInfo);
fontInfo.FontFamily = 54;
fontInfo.FontWeight = 300;
fontInfo.nFont = 0;
const wchar_t myFont[] = L"KaiTi";
fontInfo.dwFontSize = { 9, 30 };
copy(myFont, myFont + (sizeof(myFont) / sizeof(wchar_t)), fontInfo.FaceName);
SetCurrentConsoleFontEx(hConsole, false, &fontInfo);
setlocale(LC_ALL, "zh_CN.UTF-8");
//wcin.imbue(locale("zh_CN.UTF-8"));
//wcout.imbue(locale("zh_CN.UTF-8"));
}
Simplified sample code:
#define _UNICODE
int main() {
prepare(); // Prepare console to output Chinese characters properly
wcin.imbue(locale("zh_CN.UTF-8"));
wcout.imbue(locale("zh_CN.UTF-8"));
wstring a = L"你好";
wcout << a; // Prints and displays properly
wstring b;
wcin >> b; // "你好"
wcout << b; // Nothing prints
return 0;
}
How can I fix this issue? Thanks!
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
