例如: #include <iostream>
using namespace std;
int main(void) { char str[] = {'中' >> 16, '中' >> 8 & 0xff, '中' & 0xff, '\0'}; cout << "Array size: " << sizeof(str) << endl; cout << str << endl; return 0; } 输出结果: Array size: 4 中
其中代码中的那个字符数组就相当于char str[] = "中";,上面只不过写了展开形式。 因此,要想输出UTF8的txt文本文件,直接用fputs或fwrite输出就行了,根本不用进行任何转换。
值得注意的是,在linux上编译上述程序的时后,会出现警告: g++ main.cpp -o main main.cpp:7:16: warning: multi-character character constant [-Wmultichar] char str[] = {'中' >> 16, '中' >> 8 & 0xff, '中' & 0xff, '\0'}; ^ main.cpp:7:29: warning: multi-character character constant [-Wmultichar] char str[] = {'中' >> 16, '中' >> 8 & 0xff, '中' & 0xff, '\0'}; ^ main.cpp:7:48: warning: multi-character character constant [-Wmultichar] char str[] = {'中' >> 16, '中' >> 8 & 0xff, '中' & 0xff, '\0'}; ^ 这是因为不同的编译器,字符常量'中'表示的整数值不同。Linux下,'中'是三字节,而在Windows下却是两字节。
|