我打算使用WriteFile方法编写ñaäïüwiç
(utf-8编码)等字符串。
所以我有以下代码:
#include <windows.h>
#include <fcntl.h>
#include <io.h>
#include <stdio.h>
int main(void) {
WCHAR str[] = L"ñaäïüwiç \n";
DWORD dwRead, dwWritten;
dwRead = (wcslen(str) + 1) * sizeof(WCHAR);
HANDLE hParentStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
BOOL bSuccess = WriteFile(hParentStdOut, str, dwRead, &dwWritten, NULL);
return 0;
}
这个小程序的作用是打印以下代码:
± a õ ´ ³ w i þ
如何解决这个问题?
答案 0 :(得分:2)
看起来您的字节被解释为ASCII。 UTF-16中的字符ñ的十六进制编码为0x00F1。 0xF1对应于ASCII代码页437中的±。 打印的其他字符也是如此。看起来像你使用UTF-16文字定义的字节不会丢失,而是被流解释为单个ASCII字节0xF1 0x00等。
请参阅此处的相关信息:How to Output Unicode Strings on the Windows Console
该帖子说您应该使用WriteConsoleW
代替。该函数的参数与WriteFile
的参数相同,只是str
应该是UTF-16:
DWORD dwToWrite, dwWritten;
dwToWrite = wcslen(str);
HANDLE hParentStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
BOOL bSuccess = WriteConsoleW(hParentStdOut, str, dwToWrite, &dwWritten, NULL);