在linux中的c程序中输入箭头键

时间:2016-08-11 15:27:50

标签: c linux

我想从用户那里获取输入并检查用户是否放弃了箭头键作为输入。我尝试了getch功能,但它只允许用户输入一个字符。我希望用户可以输入上/下箭头键或包含多个字符的任何字符串。稍后我想检查用户是否放弃/关闭键作为输入或其他字符串。请帮助。

1 个答案:

答案 0 :(得分:0)

如果你必须坚持不看here找到答案......

  

我试过这个,但是我的编译器不支持conio lib,所以我不能使用getch函数。

为什么需要使用getch()?您可以轻松使用任何其他功能来获取输入并为您完成工作。

  

其次我希望能够输入字符串,所以我必须使用像fgets()这样的函数。

在我的例子中,如果你愿意,我已经使用了fgets()

  

但问题是fgets()不要将箭头视为输入。还有其他办法吗?

在终端上输入向上箭头时,每台计算机上可能看起来不同。例如,当我输入向上箭头时,在我的计算机上,它看起来像这样:^[[A。但是看起来,fgets() 确实将箭头作为输入。正如您在链接问题中看到的那样:

  

按一个箭头键getch将三个值推入   缓冲液:

     
      
  • '\033'
  •   
  • '['

  •   
  • 'A', 'B', 'C' or 'D'

  •   

'A'代表向上箭头,'B'代表向下箭头,'C'代表右箭头,'D'代表你输入左箭头。在我的例子中,我只处理向上箭头,但是应该很容易调整程序来检测其他箭头。

现在举例:

#include <stdio.h>
#include <string.h>

#define MAX_STRING_SIZE 100

void flush_input(char userInput[]);

int main(void) {
  char input[MAX_STRING_SIZE] = {0};
  int i;
  int upArrow = 0; //1 if up arrow found, 0 if not found

  printf("Enter anything with an up arrow key (or not if you so choose):\n");
  fgets(input, sizeof(input), stdin);
  flush_input(input);

  size_t inputLen = strlen(input);

  for (i = 0; i < (int)inputLen; i++) {
    if (input[i] == '\33') {
      if(input[i+2] == 'A') {
        upArrow = 1;
      }
    }
  }

  if (upArrow != 0) {
    printf("You entered an up arrow somewhere in the input\n");
  } else {
    printf("You did not enter an up arrow anywhere\n");
  }
  return 0;
}


void flush_input(char userInput[]) {
  if(strchr(userInput, '\n') == NULL) {
    /* If there is no new line found in the input, it means the [enter] character
    was not read into the input, so fgets() must have truncated the input
    therefore it would not put the enter key into the input.  The user would
    have typed in too much, so we would have to clear the buffer. */
    int ch;
    while ( (ch = getchar()) != '\n' && ch != EOF );
  } else {
    //If there is a new line, lets remove it from our input.  fgets() did not need to truncate
    userInput[strcspn(userInput, "\r\n")] = 0;
  }
}

我们通过检查是否有'\033'来检测向上箭头(请注意,如果使用这样的八进制代码,则不需要0,因此检查'\33'也有效),如果有是的,然后我们用'['检查前面的两个字符(跳过if(input[i+2] == 'A'))。如果这是真的,我们知道将输入一个向上箭头键。

让我们运行一些示例测试(请记住,在我的终端中,向上箭头键看起来像^[[A):

user@user Stack Overflow $ ./a.out
Enter anything with an up arrow key (or not if you so choose):
hello^[[A
You entered an up arrow somewhere in the input
user@user Stack Overflow $ ./a.out
Enter anything with an up arrow key (or not if you so choose):
bye bye
You did not enter an up arrow anywhere

因此,总而言之,我不知道为什么您认为possible duplicate无效,因为您无法使用getch()。用于获取输入的函数完全不相关。此过程中唯一重要的部分是了解如何在终端中输入箭头键。