使用 while(getchar()!='\n') 我清空标准输入,但我必须按下 Enter 键

Using while(getchar()!='\n') I empty the stdin, but I have to push on Enter key

我正在使用 while(getchar()!='\n') 来清空我的标准输入,但有时如果我想继续,我需要按下 Enter 键,这样计算才能继续...为什么?我将 post 部分代码:

while(1){
   if(fgets(buffer,MAX_DIMENSION,stdin)==NULL){ perror("Error"); exit(1);}
   }else{
       printf("Not correct term\n");
       while(getchar()!='\n');
       sleep(1); 
   }
}

谢谢!

@iharob 如果我设置 MAX_DIMENSION=1240 并作为输入发送:一个字符串 > 1024 它仍然在标准输入上,所以我必须使用 while(getchar()!='\n')

fgets() 函数,从 stdin 中捕获 '\n',您正在使用 getchar()stdin 中提取 '\n' 但是它已经被 fgets() 消耗掉了,这就是为什么你需要额外的 \'n'.

而且,你不检查是否 getchar() returns EOF 而不是一个字符。在我看来,while (1) 循环,很难遵循逻辑

char buffer[MAX_DIMENSIONS];
while (fgets(buffer, sizeof(buffer), stdin) == NULL)
{
   printf("Not correct term\n");
   sleep(1); 
}

会更好

您已使用 fgets 获取字符串。该字符串以换行符终止。然后,您试图通过使用 getchar empty stdin 并将某些内容放入 getchar,您必须输入另一个换行符。如果这是您想要的,您可以简单地忽略 fgets 之后的缓冲区。不需要使用getchar清空缓冲区。

2 个问题:

1: 代码有额外的 }.

//                                                                   here
if(fgets(buffer,MAX_DIMENSION,stdin)==NULL){ perror("Error"); exit(1);}
}else{
// or at the beginning

2:假设以上不是问题,那么正如 回答的那样,通常 fgets() 包含 '\n' 并且不需要 empty stdin.

然而,当行过长并且 '\n' 未被 fgets() 读取时,读取直到找到结尾是有意义的。

  if (fgets(buffer, MAX_DIMENSION, stdin) == NULL) {
    perror("Error");
    exit(1);
  }
  if (strchr(buffer, '\n') == NULL) {
    int ch;
    printf("Not correct term\n");
    while (((ch = getchar()) != '\n') && (ch != EOF))
      ;
    // while(getchar()!='\n');
    sleep(1);
  }