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

第二次通过循环,getchar()是在Enter你输入的第一个字符之后。

你可以做类似的事情

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

Enter在得到一个 char 之后和要求另一个之前摆脱一切,包括下一个。

于 2011-12-04T02:29:42.337 回答
0

如果您想在输入稍微高级的技术时检查字符,请将标准输入的行为更改为原始模式。然后,一旦用户点击一个字符,您就会在变量中得到它。 检查这个开始

于 2011-12-04T02:46:32.380 回答
0

用于CTRL + D获取没有副作用的换行符的功能。

于 2011-12-04T03:05:03.713 回答