Jens Asked:2020-09-06 06:18:24 +0000 UTC2020-09-06 06:18:24 +0000 UTC 2020-09-06 06:18:24 +0000 UTC 在控制台中使用 unicode 772 我正在使用 MS VS 201,Win 7。以下代码输出错误的字符: system("chcp 65001"); std::cout << "\x00FF" << std::endl; 问题是什么?即使更改了代码页,控制台也对 Unicode 不友好? c++ 2 个回答 Voted Best Answer MSDN.WhiteKnight 2020-09-06T13:31:12Z2020-09-06T13:31:12Z 不,Windows 控制台是 unicode 友好的,无需设置代码页。您可以通过运行以下代码轻松验证这一点: HANDLE consoleHandle = GetStdHandle(STD_OUTPUT_HANDLE); wchar_t str[]=L"\x00FF\n"; WriteConsoleW(consoleHandle,str,wcslen(str),NULL,NULL); 但是,这并不能解决问题,因为它仅适用于控制台。如果标准输出被重定向到一个文件,一切都会被破坏。可以从 WriteConsole 切换到 WriteFile,但这不是很方便。 如果您需要 UTF-8,在 VS 2015+ 中它的工作方式如下: #include <string> #include <iostream> #include <Windows.h> #include <cstdio> int main() { SetConsoleOutputCP(CP_UTF8); setvbuf(stdout, NULL, _IOFBF, 1000); std::cout << u8"\x00FF" << std::endl; } VS2010+ 支持的更传统的方式仍然是使用中间宽字符: #include <stdio.h> #include <stdlib.h> #include <stddef.h> #include <io.h> #include <fcntl.h> #include <iostream> int main() { _setmode(_fileno(stdout), _O_U8TEXT); std::wcout << L"\x00FF" << std::endl; } user245150 2020-09-06T15:26:04Z2020-09-06T15:26:04Z 在开始之前,请确保控制台中的字体支持该字符。 #include <io.h> #include <iostream> //debug #include <fcntl.h> int wmain(int argc, wchar_t* argv[]) { _setmode(_fileno(stdout), _O_U16TEXT); _setmode(_fileno(stdin), _O_U16TEXT); _setmode(_fileno(stderr), _O_U16TEXT); std::wcout << L"\x00FF" << std::endl; system("pause"); return 0; }
不,Windows 控制台是 unicode 友好的,无需设置代码页。您可以通过运行以下代码轻松验证这一点:
但是,这并不能解决问题,因为它仅适用于控制台。如果标准输出被重定向到一个文件,一切都会被破坏。可以从 WriteConsole 切换到 WriteFile,但这不是很方便。
如果您需要 UTF-8,在 VS 2015+ 中它的工作方式如下:
VS2010+ 支持的更传统的方式仍然是使用中间宽字符:
在开始之前,请确保控制台中的字体支持该字符。