例如:
#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下卻是兩字節。