我正在阅读有关 string 和 wstring 的众所周知的答案,并出现一些困惑。
\n\n源字符集和执行字符集均设置为utf-8,Windows x64,VC++编译器,git bash控制台(可以打印unicode字符),系统默认代码页936(GB2312)。
\n\n我的专业代码:
\n\n#include <cstring>\n#include <iostream>\nusing namespace std;\nint main(int argc, char* argv[])\n{\n wchar_t c[] = L"ol\xc3\xa9";\n wchar_t d[] = L"abc";\n wcout << c << endl;\n wcout << d << endl;\n\n return 0;\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n可以打印“abc”,但无法打印“\xc3\xa9”。
\n\n据我所知,它wchar_t
与L
前缀字符串文字一起使用。而在Windows下wchar_t
是用UTF-16编码的(这是硬编码的吧?无论我选择什么源字符集或执行字符集,L"abc"
总是有相同的UTF-16代码单元)。
问题是\xef\xbc\x9a怎么可能是wcout
UTF-16编码的字符串(“abc”),而我的源文件是utf-8,执行字符集是utf-8。除非我将所有内容都设置为 utf-16,否则该程序应该无法识别 UTF-16 编码的内容。
如果它可以以某种方式打印 UTF-16,那为什么它不能打印呢\xc3\xa9
?
您需要非标准 Windows 系统调用来启用 UTF-16 输出。
\n\n#include <iostream>\n#include <io.h>\n#include <fcntl.h>\n#include <stdio.h>\n\nint main()\n{\n _setmode(_fileno(stdout), _O_U16TEXT); // <=== Windows madness\n std::wcout << L"ol\xc3\xa9\\n";\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n请注意,执行此操作后您将无法使用cout
,只能使用wcout
.
另请注意,您的源代码文件必须具有 BOM,否则编译器将无法将其识别为 Unicode。
\n 归档时间: |
|
查看次数: |
3539 次 |
最近记录: |