-1

我有这个循环,但是当我在我的角色之后按 Enter 键时,它会对其进行处理,然后在再次要求输入之前处理 '\n'。请!!!!帮助

int input;



      while (true){
        input = getchar(); 
        fflush(NULL);
        input = input - '0';
        if( input != 'e' && input != '\n') {
            rc = state_fun(input);
        }

5[ENTER]处理 5 作为输入,然后将 10(即 ascii '\n')作为输入,然后再次请求输入。它让我发疯

4

2 回答 2

0
int input;
while(true) {
    input = getchar();
    getchar(); // <------
    fflush(NULL);
    input = input - '0';
    if( input != 'e' && input != '\n') {
        rc = state_fun(input);
    }
}

添加一个额外的getchar()将解决您的问题。这是因为5 Enter将 2 个字符放在stdin: a'5'和 a上'\n',这是您可能没想到的。

于 2016-04-09T05:51:09.417 回答
0

您可以关闭控制台的回显功能,如果不是,则仅回显一个字符'\n'。如果你使用linux,你可以使用这个代码:

#include <termios.h>
#include <stdio.h>
#include <unistd.h>
int main(){
    struct termios old, new;
    int nread;

    /* Turn echoing off and fail if we can't. */
    if (tcgetattr (STDIN_FILENO, &old) != 0)
      return -1;
    new = old;
    new.c_lflag &= ~(ECHO|ICANON);
    if (tcsetattr (STDIN_FILENO, TCSAFLUSH, &new) != 0)
      return -1;

    char input;
    while (1)
    {
        input = getchar();
        if (input!='\n')
            putchar(input);
    }

    /* Restore terminal. */
    tcsetattr (STDIN_FILENO, TCSAFLUSH, &old);
}

请参阅隐藏终端上的密码输入

于 2016-04-09T05:18:47.653 回答