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