C++ 字符串中写入中文字符的两种方法 - 详解与示例
在C++中,可以使用以下两种方式在字符串中写入中文字符:\n\n1. 使用Unicode转义序列:在字符串中使用\u后跟4个十六进制数字表示Unicode码点。例如,\u4e2d\u6587代表中文字符"中文"。示例代码如下:\n\ncpp\n#include <iostream>\n#include <string>\n\nint main() {\n std::string str = "\u4e2d\u6587";\n std::cout << str << std::endl; \n return 0;\n}\n\n\n2. 使用UTF-8编码:在源代码文件中使用UTF-8编码,并直接在字符串中写入中文字符。示例代码如下:\n\ncpp\n#include <iostream>\n#include <string>\n\nint main() {\n std::string str = "中文";\n std::cout << str << std::endl; \n return 0;\n}\n\n\n无论使用哪种方式,都需要确保源代码文件的编码与编译器的设置相匹配。在某些情况下,还可能需要设置编译器选项或源代码文件的BOM(Byte Order Mark)来正确处理中文字符。
原文地址: http://www.cveoy.top/t/topic/p4tV 著作权归作者所有。请勿转载和采集!