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 ステートメント (Yes/No と答える必要があります) が出力として 2 回表示されます。enter、つまり「\n」を別の文字と見なすため、これが発生していることを理解しています。fflush を使用しても、無限ループになるため役に立ちません。最後のステートメントが一度だけ表示されるようにするには、他にどのように変更できますか?

4

4 に答える 4

1

ループを使用して、残っている文字を読み取ることができますgetchar()

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

chshould intasの型はをgetchar()返しますint。かどうかも確認する必要chがありEOFます。

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 chchar 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 に答える