将getch()转换为ascii字符

时间:2011-09-21 12:37:31

标签: c++ ascii centos

我在linux上使用ncurses。我使用getch()从输入流中获取下一个键,但它返回的数字不是字母。

在谷歌上做研究后,我发现getch()不是标准的,所以我不知道该怎么做。

我需要键0-9,制表符,ctrl,p,v,m,l,a,b,c,d,e,f和箭头键以及0xff,0x4F00,0x4700,0x4800, 0x5000,0x4D00:,0x4B00,0x4900,0x5100。这些是在针对getch()的返回值的if语句中使用的。

这是我试图重新创建的程序的Windows版本中的代码。

    unsigned long nr;
if( GetNumberOfConsoleInputEvents(ConH,&nr) )
{
    if( nr > 0 )
    {
        INPUT_RECORD ipr;
        ReadConsoleInput(ConH,&ipr,1,&nr);
        if( ipr.EventType == KEY_EVENT && ipr.Event.KeyEvent.bKeyDown )
        {
            int key = ipr.Event.KeyEvent.uChar.AsciiChar;
            if( key == 0 ) key = ipr.Event.KeyEvent.wVirtualScanCode<<8;
            return key;
        }
    }
}
return 0;

是否有一个函数可以用于getch()的结果,所以我可以按下实际键,比如上面的.AsciiChar?

1 个答案:

答案 0 :(得分:5)

MAJOR EDIT 摆脱以前的例子,试试这个大例子。

getch()的返回值是ASCII字符,或某些特殊键的curses名称。

这是一个可能明确指出的程序:

#include <ncurses.h>
#include <cctype>

int main(int ac, char **av) 
{
    WINDOW* mainWin(initscr());
    cbreak();
    noecho();

    // Invoke keypad(x, true) to ensure that arrow keys produce KEY_UP, et al,
    // and not multiple keystrokes.
    keypad(mainWin, true);

    mvprintw(0, 0, "press a key: ");
    int ch;

    // Note that getch() returns, among other things, the ASCII code of any key
    // that is pressed. Notice that comparing the return from getch with 'q'
    // works, since getch() returns the ASCII code 'q' if the users presses that key.
    while( (ch = getch()) != 'q' ) {
      erase();
      move(0,0);
      if(isascii(ch)) {
        if(isprint(ch)) {
          // Notice how the return code (if it is ascii) can be printed either
          // as a character or as a numeric value.
          printw("You pressed a printable ascii key: %c with value %d\n", ch, ch);
        } else {
          printw("You pressed an unprintable ascii key: %d\n", ch);
        }
      }

      // Again, getch result compared against an ASCII value: '\t', a.k.a. 9
      if(ch == '\t') {
        printw("You pressed tab.\n");
      }

      // For non-ASCII values, use the #define-s from <curses.h>
      switch(ch) {
      case KEY_UP:
        printw("You pressed KEY_UP\n");
        break;
      case KEY_DOWN:
        printw("You pressed KEY_DOWN\n");
        break;
      case KEY_LEFT:
        printw("You pressed KEY_LEFT\n");
        break;
      case KEY_RIGHT:
        printw("You pressed KEY_RIGHT\n");
        break;
      }
      printw("Press another key, or 'q' to quit\n");
      refresh();
    }

    endwin();
}

<强>参考