簡體   English   中英

如何使用 Visual Studio 將 Unicode 打印到 C 中的輸出控制台?

[英]How do I print Unicode to the output console in C with Visual Studio?

正如問題所說,我必須做什么才能將 Unicode 字符打印到輸出控制台? 我必須使用哪些設置? 現在我有這個代碼:

wchar_t* text = L"the 來";
wprintf(L"Text is %s.\n", text);
return EXIT_SUCCESS;

它打印: Text is the ?.

我嘗試將輸出控制台的字體更改為 MS Mincho、Lucida Console 和其他一些字體,但它們仍然不顯示日文字符。

那么,我該怎么辦?

這是對我有用的代碼 (VS2017) - 啟用 Unicode 的項目

#include <stdio.h>
#include <io.h>
#include <fcntl.h>

int main()
{
    _setmode(_fileno(stdout), _O_U16TEXT);
    wchar_t * test = L"the 來. Testing unicode -- English -- Ελληνικά -- Español." ;

    wprintf(L"%s\n", test);
}

這是控制台

輸出

將其復制到 Notepad++ 后,我看到了正確的字符串

來。 測試 unicode -- 英語 -- Ελληνικά -- 西班牙語。

操作系統 - Windows 7 英文,控制台字體 - Lucida 控制台

基於評論的編輯

我試圖修復上面的代碼以在 Windows 10 上與 VS2019 一起工作,我能想到的最好的就是這個

#include <stdio.h>
int main()
{
    const auto* test = L"the 來. Testing unicode -- English -- Ελληνικά -- Español.";

    wprintf(L"%s\n", test);
}

當它“按原樣”運行時,我看到默認控制台設置

當它在控制台設置為喜歡 Lucida Console 和 UTF-8 編碼的情況下運行時,我看到控制台切換到 UTF-8

作為顯示為空矩形的來字符的答案 - 我想是不包含所有 Unicode gliphs 的字體的限制

當文本從最后一個控制台復制到 Notepad++ 時,所有字符都正確顯示

問號通常表示 Windows 無法將字符轉換為目標代碼頁。 在控制台中,空心方塊表示 Unicode 字符已正確接收但無法顯示,因為控制台字體不支持它,或者它是一個需要 Uniscribe 的復雜腳本,控制台無法處理。 您可以復制正方形並將其粘貼到記事本/寫字板中,它應該可以正確顯示。

WriteConsoleW Windows 函數可以顯示 Unicode 字符,並且可以一直工作到 Windows NT。 它只能寫入控制台,因此在重定向輸出時必須改用WriteFile GetConsoleMode在重定向句柄上失敗。

你沒有說你使用的是哪個 VS 版本,而且這些年來情況發生了變化,但是如果你調用_setmode(_fileno(stdout), _O_U16TEXT); Unicode 輸出自 VS2005 以來一直不錯_setmode(_fileno(stdout), _O_U16TEXT); 在 main() 早期:

#include <stdio.h>
#include <io.h>
#include <fcntl.h>

int main()
{
    _setmode(_fileno(stdout), _O_U16TEXT); // Call this before writing anything

    wchar_t * test = L"the 來" ;
    wprintf(L"Text is %s.\n", test);
    return 0;
}

另請參閱: 控制台中的神話破壞

字符“來”可能不在您的系統字符代碼頁中。 您需要將字符保存為 utf-8。

在 vs2013 中,我試試這個:

// save as utf-8
#pragma execution_character_set( "utf-8" )

#include <Windows.h>

char *s = "the 來";

int main(){
    // set console code page to utf-8
    SetConsoleOutputCP(65001);
    printf("%s\n",s);
    return 0;
}

這對我有用:

#include <locale.h>

在主函數中,

setlocale(LC_ALL, "en_US.UTF-8");

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM