3

while ループで printf() 関数の二重入力が表示される理由を誰かが説明してくれますか?

#include <ctype.h>
#include <stdio.h>

int main(){
    int x = 0;

    while ( x != 'q'){

    printf("\nEnter a letter:");

    x=getchar();
    printf("%c\n", x);
    if( isalpha(x) )
      printf( "You entered a letter of the alphabet\n" );
    if( isdigit(x) )
      printf( "You entered the digit %c\n", x);
    }   
    return 0;
}

Debian Squeeze (gcc バージョン 4.4.5 (Debian 4.4.5-8)) のコードの出力は次のとおりです。

Enter a letter:1
1
You entered the digit 1

Enter a letter: // why is the first one appearing ???


Enter a letter:2
2
You entered the digit 2
4

4 に答える 4

5

最初のものは、1 の後に Enter を押したときに入力した行末記号文字を読み取ります (行末記号は入力バッファーに残ります)。

これは、else ブランチを追加することで確認できます。

#include <ctype.h>
#include <stdio.h>

int main()
{
  int x = 0;
  while ( x != 'q')
  {
    printf("\nEnter a letter:");
    x = getchar();
    printf("%c\n", x);
    if( isalpha(x) )
      printf( "You entered a letter of the alphabet\n" );
    else if( isdigit(x) )
      printf( "You entered the digit %c\n", x);
    else
      printf("Neither letter, nor digit: %02X\n", x);
  }
  return 0;
}

出力:

Enter a letter:1
1
You entered the digit 1

Enter a letter:

Neither letter, nor digit: 0A

Enter a letter:2

バイト0Aは改行文字です。

于 2011-12-04T02:24:40.360 に答える
1

2回目のループでは、最初に入力した文字getchar()の後に取得します。Enter

あなたは次のようなことをすることができます

while ((c = getchar()) != EOF && c != '\n') {} /* eat the rest of the line */

Enter文字を取得した後、別の文字を要求する前に、次の文字を含むすべてを取り除くため。

于 2011-12-04T02:29:42.337 に答える
0

少し高度な手法を入力するときに文字をチェックしたい場合は、stdin の動作を raw モードに変更することです。その後、ユーザーが文字をヒットするとすぐに、変数にそれを取得します。 いくつかの開始のためにこれを確認してください

于 2011-12-04T02:46:32.380 に答える
0

CTRL + D副作用なしで改行文字の機能を取得するために使用します。

于 2011-12-04T03:05:03.713 に答える