0

我刚开始使用 C 编程,当我试图编写一个只接受 y 或 n 个字符的程序时,我遇到了

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

int main()
{
  char ch;
  printf("Do you want to continue\n");

  for (;;)
    {
      ch=getchar();
      if (ch=='Y' || ch=='y')
        {
            printf("Sure!\n");
            break;
        }
        else if (ch=='N'||ch=='n')
        {
            printf("Alright! All the best!\n");
            break;
        }
        else
        {
            printf("You need to say either Yes/No\n");
            fflush(stdin);
        }

    }
    return(0);
}

当我运行此代码并输入除 Y/y 或 N/n 之外的任何其他字符时,我会收到最后一个 printf 语句(您需要说是/否)作为输出两次。我知道发生这种情况是因为它认为输入,即 '\n' 作为另一个字符。使用 fflush 无济于事,因为它是一个无限循环。我还能如何修改它以使最后一条语句只显示一次?

4

4 回答 4

1

您可以使用循环读取使用以下命令留下的任何字符getchar()

  ch=getchar();
  int t;
  while ( (t=getchar())!='\n' && t!=EOF );

chshould intas的类型getchar()返回一个int. 您还应该检查是否chEOF.

fflush(stdin)根据 C 标准是未定义的行为。虽然它是为某些平台/编译器(如 Linux 和 MSVC )定义的,但您应该在任何可移植代码中避免使用它。

于 2015-12-13T00:04:27.440 回答
0

另一种选择 - 使用scanf忽略空格。

而不是ch=getchar();,只需要scanf( " %c", &ch );

有了这个你也可以摆脱fflush(stdin);

于 2015-12-13T00:06:49.733 回答
0

就像我的评论中所说的那样,你应该使用int ch而不是char ch因为它的返回类型getcharint.

要清洁stdin,您可以执行以下操作:

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

int main(void){
  int ch,cleanSTDIN;
  printf("Do you want to continue\n");

  for (;;)
    {
      ch = getchar();
      while((cleanSTDIN = getchar()) != EOF && cleanSTDIN != '\n');
      if (ch=='Y' || ch=='y')
        {
            printf("Sure!\n");
            break;
        }
        else if (ch=='N'||ch=='n')
        {
            printf("Alright! All the best!\n");
            break;
        }
        else
        {
            printf("You need to say either Yes/No\n");
        }

    }
    return(0);
}

任何方式都可能会为您完成这项工作:

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

int main(void){
    char ch;
    int check;

    do {
        printf("Do you want to continue: ");

        if ((scanf("%c",&ch)) == 1){
            while((check=getchar()) != EOF && check != '\n');

            if ((ch == 'y') || (ch == 'Y')){
                printf("Alright! All the best!\n");
                break;
            } else if((ch == 'n') || (ch == 'N')){
                printf("You choosed %c\n",ch);
                break;
            }else{
                printf("You need to say either Yes/No\n");
            }
        }else{
            printf("Error");
            exit(1);
        }

    }while (1);

    return 0;
}

输出1:

Do you want to continue: g
You need to say either Yes/No
Do you want to continue: y
Alright! All the best!

输出2:

Do you want to continue: n
You choosed n
于 2015-12-13T00:07:43.097 回答
0

或者我们可以简单地在 last 之后使用另一个break;语句printf()

于 2018-02-01T11:52:47.237 回答