繁体   English   中英

printf()在while循环中的奇怪行为

[英]strange behavior of printf() inside a while loop

有人可以解释一下为什么我看到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

第一个读取在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是换行符。

第二次循环, getchar()在您输入的第一个char后获得Enter

你可以做点什么

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

在获得一个字符之后,在要求另一个之前,去除所有内容,包括下一个Enter

如果要在输入稍微高级的技术时检查字符,则将stdin的行为更改为原始模式。然后,只要用户点击char,就会在变量中得到它。 检查一下这个开始

使用CTRL + D获取换行符的功能而不会产生副作用。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM