1

コンソール アプリケーションに次のループがあります。

do{
    printf("\n %sVotre choix :%s ",GREEN_BOLD,RESETCOLOR);
    choix = tolower(getchar());
}while((choix != 'c') && (choix != 'l') && (choix != 'e') && (choix != 's'));

したがって、ユーザーがcle、またはのいずれでもない文字を入力するとs、メッセージVotre choix : が再度表示され、プログラムはユーザーが別の文字を入力するのを待ちますが、問題は、ユーザーがそのメッセージを 2 回受け取ることです。ユーザーが文字を入力して を打つReturnと、次の反復でReturn文字として読み取られるため、これは私が得ているもののスクリーンショットです:

別のスクリーンショット

Returnアプリケーションがを文字として読み取らないようにするにはどうすればよいですか?

4

1 に答える 1

0

" %c"「Return」を含む前の空白を最初に消費するために使用し、次に 1 を読み取りますchar

char choix = 0;
do {
  printf("\n %sVotre choix :%s ",GREEN_BOLD,RESETCOLOR);
  // choix = tolower(getchar());
  scanf(" %c", &choix);
  choix = tolower(choix);
} while((choix != 'c') && (choix != 'l') && (choix != 'e') && (choix != 's'));

より良いアプローチは、fgets() sscanf()チームを使用することです。

char choix;
do {
  printf("\n %sVotre choix :%s ",GREEN_BOLD,RESETCOLOR);
  char buf[10];
  if (fgets(buf, sizeof buf, stdin) == NULL) break; // EOF or I/O error
  if (sscanf(buf, " %c", &choix) != 1) continue;
  choix = tolower(choix);
} while((choix != 'c') && (choix != 'l') && (choix != 'e') && (choix != 's'));
于 2013-10-23T18:55:39.137 に答える