我正在嘗試列印無窮大符號 (∞),但我一直在收到垃圾。我已經嘗試了這里提到的所有內容,但沒有任何效果。
我想要完成的是這個
modifies strength by 9 ∞
我試過了
printf ("%c", 236);
printf ("%c", 236u);
我得到
modifies strength by 9 ì
我試過了
printf("∞");
我得到
modifies strength by 9 ?
我試過這個
if ( paf->duration == -1 ){
setlocale(LC_ALL, "en_US.UTF-8");
wprintf(L"%lc\n", 8734);
ch->printf("∞");
只是想看看我是否可以讓 wprintf 列印它,但它完全忽略了 setlocale 和 wprintf 并且仍然給了我
modifies strength by 9 ?
我試過
if ( paf->duration == -1 ){
std::cout << "\u221E";
ch->printf("∞");
但是得到了這個警告和錯誤
Error C2664 'int _CrtDbgReportW(int,const wchar_t *,int,const wchar_t *,const wchar_t *,...)': cannot convert argument 5 from 'int' to 'const wchar_t *' testROS1a C:\Program Files (x86)\Windows Kits\10\Include\10.0.19041.0\ucrt\malloc.h 164
Warning C4566 character represented by universal-character-name '\u221E' cannot be represented in the current code page (1252) testROS1a C:\_Reign of Shadow\TEST\src\CPP\act_info.cpp 3724
我無法做出正面或反面。我已經用盡了我的知識范圍,所以有人知道如何做到這一點嗎?
uj5u.com熱心網友回復:
這在我的機器上實作了,windows 代碼頁(1252),但不確定這有多普遍。我從來沒有真正接觸過 unicode/本地化的東西。而且似乎總有一個問題。
#include <iostream>
#include <io.h>
#include <fcntl.h>
const wchar_t infinity_symbol = 0x221E;
int main()
{
// enable windows console to unicode
_setmode(_fileno(stdout), _O_U16TEXT);
std::wcout << infinity_symbol;
}
uj5u.com熱心網友回復:
要使用帶有寬字串的 Windows 命令提示符,請按如下方式更改模式,直到模式切換回后,printf/cout 才會作業。確保在模式更改之間重繪 :
#include <iostream>
#include <io.h>
#include <fcntl.h>
using namespace std;
int main()
{
// To use wprintf/wcout and output any BMP (<= U FFFF) code point
int org = _setmode(_fileno(stdout), _O_U16TEXT);
wcout << L'\u221e' << endl;
wprintf(L"\u221e\n");
fflush(stdout);
_setmode(_fileno(stdout), org); // to switch back to cout/printf and default code page
cout << "hello, world!" << endl;
printf("hello, world!\n");
}
輸出:
∞
∞
hello, world!
hello, world!
如果您使用 UTF-8 源代碼并且您的編譯器接受它,您還可以將終端的代碼頁更改為 65001 (UTF-8),它可以按printf原樣使用:
測驗.c
#include <stdio.h>
int main() {
printf("∞\n");
}
控制臺輸出:
C:\demo>cl /W4 /utf-8 /nologo test.c
test.c
C:\demo>chcp
Active code page: 437
C:\demo>test ## NOTE: Wrong code page prints mojibake.
Γê? ## These are UTF-8 bytes interpreted incorrectly.
C:\demo>chcp 65001
Active code page: 65001
C:\demo>test
∞
uj5u.com熱心網友回復:
Windows 中的最佳選擇是使用 UTF16,_setmode如其他答案所示。您還_setmode可以在 Unicode 和 ANSI 之間來回切換。
警告 C4566:無法在當前代碼頁中表示由通用字符名稱“\u221E”表示的字符 (1252)
那是因為您的 *.cpp 檔案可能以 Unicode 格式保存,編譯器將其∞視為 2 位元組 UTF16 wchar_t( '\u221E') 并且無法將其轉換為char.
printf("\xEC")可能會列印∞,但僅限于英語系統,并且僅當控制臺字體感覺像那樣解釋它時。即使它有效,如果您更改一些小設定,它明天可能會停止作業。這是舊的 ANSI 編碼,有很多問題,這就是引入 Unicode 的原因。
您可以在帶有 C 20 的 Visual Studio 中使用此替代解決方案:
SetConsoleOutputCP(CP_UTF8);
printf((const char*)u8"∞");
這個在 Visual Studio 和 C 17 中的解決方案:
SetConsoleOutputCP(CP_UTF8);
printf(u8"∞");
誰知道以后會發生怎樣的變化。
但 UTF16 至少在本機上得到支持。wprintf,wcout與_setmode更一致。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/335367.html
