簡體   English   中英

無法從 NCURSES 中的 stdin 擴展 ASCII 字符讀取

[英]Cannot read from stdin extended ASCII character in NCURSES

我在嘗試讀取 NCURSES 中的擴展 ASCII 字符時遇到問題。

我有這個程序:

#include <ncurses.h>
int main () {
    initscr();
    int d = getch();
    mvprintw(0, 0, "letter: %c.", d);
    refresh();
    getch();
    endwin();
    return 0;
}

我使用以下命令構建它:gcc -lncursesw ac

如果我在 7 位 ascii 中輸入一個字符,比如“e”字符,我會得到:

letter: e.

然后我必須鍵入另一個程序才能結束。

如果我在擴展的 ascii 中輸入一個字符,比如 'á' 字符,我會得到:

letter:  .

程序結束。

它就像第二個字節被讀取為另一個字符。

我怎樣才能得到正確的字符 'á' ???

謝謝!

您要鍵入的字符需要程序設置語言環境 手冊中所述:

Initialization

   The  library uses the locale which the calling program has
   initialized.  That is normally done with setlocale:

         setlocale(LC_ALL, "");

   If the locale is not initialized, the library assumes that
   characters  are  printable  as in ISO-8859-1, to work with
   certain legacy programs.  You should initialize the locale
   and  not  rely on specific details of the library when the
   locale has not been setup.

除此之外,您的語言環境很可能使用 UTF-8。 要使用 UTF-8,您應該針對ncursesw庫進行編譯和鏈接。

此外, getch函數僅返回單字節編碼的值,例如 ISO-8859-1,有些人將其與Windows cp1252混淆,然后返回“擴展 ASCII”(這說明了兩個無法抵消的謬誤)。 UTF-8 是一種多字節編碼。 如果您使用getch讀取該內容,您將獲得該字符的第一個字節。

相反,要讀取UTF-8 ,您應該使用get_wch (除非您想自己解碼 UTF-8)。 這是一個修改后的程序,它可以做到:

#include <ncurses.h>
#include <locale.h>
#include <wchar.h>
int
main(void)
{   
    wint_t value;
    setlocale(LC_ALL, "");
    initscr();
    get_wch(&value);
    mvprintw(0, 0, "letter: %#x.", value);
    refresh();
    getch();
    endwin();
    return 0;
}

我將結果打印為數字,因為printw不知道 Unicode 值。 printw使用與printf相同的 C 運行時支持,因此您可以直接打印值。 例如,我看到POSIX printf有一個用於處理wint_t的格式化選項:

c
int參數應轉換為unsigned char ,並寫入結果字節。
如果存在l ( ell ) 限定符,則wint_t參數將被轉換為好像由沒有精度的ls轉換規范和指向wchar_t類型的二元素數組的參數一樣,其中的第一個元素包含wint_t參數到ls轉換規范,第二個元素包含空寬字符。

由於 ncurses 適用於許多平台,並非所有平台都支持該功能。 但是您可能會假設它適用於 GNU C 庫:大多數發行版通常都提供可行的語言環境配置。

這樣做,這個例子更有趣:

#include <ncurses.h>
#include <locale.h>
#include <wchar.h>
int
main(void)
{   
    wint_t value;
    setlocale(LC_ALL, "");
    initscr();
    get_wch(&value);
    mvprintw(0, 0, "letter: %#x (%lc).", value, value);
    refresh();
    getch();
    endwin();
    return 0;
}

暫無
暫無

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

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