使用 fgetc(stdin) 时的未定义行为

undefined behaviour while using fgetc(stdin)

在问这个问题之前,我已经阅读了:fgetc(stdin) in a loop is producing strange behaviour。我正在编写一个程序来询问用户是否要退出。这是我的代码:

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

int ask_to_exit()
{
    int choice;
    while(choice!='y'||choice!='n')
    {   printf("Do you want to continue?(y/n):");
        while((fgetc(stdin)) != '\n');
        choice = fgetc(stdin);
        if(choice=='y') return 0;
        else if(choice=='n') return 1;
        else printf("Invalid choice!\n");
    }
}

int main()
{
    int exit = 0;
    while(!exit)
    {
        exit = ask_to_exit();
    }
    return 0;
}

因为 fflush(stdin) 是未定义的行为,所以我没有使用它。按照另一个问题的解决方案后,我仍然得到错误。这是上面程序的测试运行:

$./a.out
Do you want to continue?(y/n):y<pressed enter key>
<pressed enter key>
Invalid choice!
Do you want to continue?(y/n):y<pressed enter key>
<pressed enter key>
Invalid choice!
Do you want to continue?(y/n):n<pressed enter key>
<pressed enter key>
Invalid choice!
Do you want to continue?(y/n):n<pressed enter key>
n<pressed enter key>
<program exits>

我在您的代码中发现了以下问题。

  1. 您在初始化之前正在使用 choice
  2. 您在将任何内容读入 choice 之前跳过了一行输入。

@WhozCraig 注意到错误:

choice!='y'||choice!='n' 总是正确的。

我建议:

int ask_to_exit()
{
   int choice;
   while ( 1 )
   {
      printf("Do you want to continue?(y/n):");
      choice = fgetc(stdin);
      if ( choice == 'y' )
      {
         return 0;
      }
      if ( choice == 'n' )
      {
         return 1;
      }

      printf("Invalid choice!\n");

      // Skip rest of the line.
      int c;`
      while( (c = fgetc(stdin)) != EOF && c != '\n');

      // If EOF is reached, return 0 also.
      if ( c == EOF )
      {
         return 0;
      }
   }
}

您需要在检查 choice 的值之前获取一些输入,否则它将被取消初始化。而且,你在抓取第一个字符之前耗尽了 left-over 输入,你应该在:

之后进行
int ask_to_exit()
{
    int choice;

    do
    {
        printf("Do you want to continue?(y/n):");
        choice = fgetc(stdin);

        while (fgetc(stdin) != '\n');

        if (choice == 'y') {
            return 0;
        } else if (choice == 'n') {
            return 1;
        } else {
            printf("Invalid choice!\n");
        }
    } while (1);
}

输出:

Do you want to continue?(y/n):g
Invalid choice!
Do you want to continue?(y/n):h
Invalid choice!
Do you want to continue?(y/n):j
Invalid choice!
Do you want to continue?(y/n):k
Invalid choice!
Do you want to continue?(y/n):m
Invalid choice!
Do you want to continue?(y/n):y
Do you want to continue?(y/n):y
Do you want to continue?(y/n):y
Do you want to continue?(y/n):n
Press any key to continue . . .