确定用户是否按Tab键

时间:2013-03-13 17:43:38

标签: c tabs

所以我正在编写一个程序,其任务是确定用户是否按下了tab。所以当他按Tab键时,我应该在控制台上打印一些东西(或者做tab tablet等)。我的问题是如何在没有用户按Enter的情况下执行此操作。我试着查看ncurses但是我找不到一个简单的例子来教我如何使用tab。

编辑: 使用Linux

2 个答案:

答案 0 :(得分:1)

从技术上讲,这不是C语言问题,而是操作系统或运行时环境问题。在POSIX系统上,您必须至少以非规范模式设置终端。

规范模式缓冲键盘输入以在需要时进一步处理它们(例如,这可以让你在应用程序看到之前删除字符)。

有很多方法可以切换到非规范模式。当然你可以使用许多不同的库ncurses等。但背后的技巧是一组名为termios的系统调用。您需要做的是读取POSIX终端的当前属性并根据您的需要进行修改。例如:

struct termios old, new;

/* read terminal attributes */
tcgetattr(STDIN_FILENO,&old);

/* get old settings */
new=old;

/* modify the current settings (common: switch CANON and ECHO) */
new.c_lflag &=(~ICANON & ~ECHO);

/* push the settings on the terminal */
tcsetattr(STDIN_FILENO,TCSANOW,&new);

do_what_you_want_and_read_every_pressed_char();

/* ok, restore initial behavior */
tcsetattr(STDIN_FILENO,TCSANOW,&old);

答案 1 :(得分:0)

您可以使用ncursesgetch()功能对输入采取行动。它会返回你按下的键的int值,你可以通过查看返回是否为9来检查选项卡。这段代码将循环显示被按下的内容,直到它是一个标签然后它退出。

#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <ncurses.h>

int main() {  
  int c;
  initscr();    /* Start curses mode */
  cbreak();
  noecho();
  while(9 != (c = getch())) {
    printw("%c\n", c);
    if(halfdelay(5) != ERR) {   /* getch function waits 5 tenths of a second */
      while(getch() == c)
        if(halfdelay(1) == ERR) /* getch function waits 1 tenth of a second */
        break;
    }
    printw("Got a %d\n", c);
    cbreak();
  }
  endwin();
  return 0; 
}