从控制台读取UTF-8字符 [英] Reading UTF-8 characters from console
本文介绍了从控制台读取UTF-8字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试从控制台为我的C ++应用程序读取UTF-8编码的波兰语字符. 我确定控制台使用此代码页(已签入属性). 我已经尝试过的:
I'm trying to read UTF-8 encoded polish characters from console for my c++ application. I'm sure that console uses this code page (checked in properties). What I have already tried:
- 使用cin-而不是zażółć",我读为"za \ 0 \ 0 \ 0 \ 0"
- 使用wcin-而不是zażółć"-与cin相同的结果
- 使用scanf-而不是'zażółć\ 0',我读为'za \ 0 \ 0 \ 0 \ 0 \ 0'
- 使用wscanf-与scanf相同的结果
- 使用getchar一次读取字符-与scanf相同的结果
在主要功能的开头,我有以下几行:
On the beginning of the main function I have following lines:
setlocale(LC_ALL, "PL_pl.UTF-8");
SetConsoleOutputCP(CP_UTF8);
SetConsoleCP(CP_UTF8);
我真的很乐意提供帮助.
I would be really greatful for help.
推荐答案
这是我用于UTF-8支持的技巧.结果是多字节字符串,可以在其他地方使用
Here is the trick I use for UTF-8 support. The result is multibyte string which could be then used elsewhere:
#include <cstdio>
#include <windows.h>
#define MAX_INPUT_LENGTH 255
int main()
{
SetConsoleOutputCP(CP_UTF8);
SetConsoleCP(CP_UTF8);
wchar_t wstr[MAX_INPUT_LENGTH];
char mb_str[MAX_INPUT_LENGTH * 3 + 1];
unsigned long read;
void *con = GetStdHandle(STD_INPUT_HANDLE);
ReadConsole(con, wstr, MAX_INPUT_LENGTH, &read, NULL);
int size = WideCharToMultiByte(CP_UTF8, 0, wstr, read, mb_str, sizeof(mb_str), NULL, NULL);
mb_str[size] = 0;
std::printf("ENTERED: %s\n", mb_str);
return 0;
}
应如下所示:
P.S.非常感谢Remy Lebeau指出了一些缺陷!
P.S. Big thanks to Remy Lebeau for pointing out some flaws!
这篇关于从控制台读取UTF-8字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文