问题描述
我的问题是字符的 scanf 被跳过,它不检查扫描字符以查看我是否想再次重复该程序,为什么会发生这种情况?
My problem is that the scanf for the character is skipped and it doesn't check scan the char to see if I want to repeat the program again or not so why this is happening?
#include <stdio.h>
#include <stdlib.h>
int main()
{
int number,check;
char rep;
printf("Program to check if number is even or odd");
while( (rep!='N') || (rep!='n') )
{
printf("\n\nPlease enter the number: ");
scanf("%d",&number);
check = number%2;
if(check != 0)
printf("\nNumber is odd.");
else
printf("\nNumber is even.");
printf("\n");
printf("Do you want to enter number again?\nY=yes\tN=no\n");
scanf("%c", &rep);
}
return 0;
}
推荐答案
将 scanf("%c", &rep);
更改为 scanf(" %c", &rep);
.
这是因为第一次输入数字时,在 stdin
中留下了 '\n'.当执行 scanf("%c", &rep);
时,那个 '\n' 立即被 scanf()
消耗并分配给 rep.由于 '\n' 既不等于 'N' 也不等于 'n',所以循环继续.
This is because a '\n' is left in
stdin
the first time you input a number. When executing scanf("%c", &rep);
, that '\n' is immediately consumed by scanf()
and assigned to rep
. Since '\n' is equal to neither 'N' nor 'n', that loop continues.
格式字符串中的前导空格,在开始读取之前丢弃所有空白字符.在您的情况下,不可见的 '\n' 将被忽略,以便您可以输入字符.
With the leading space in the format string, all whitespace characters are discarded before reading starts. In your case, the invisible '\n' will be ignored, so that you can input a character.
另外,你应该写
char rep = 0;
,以防rep
的原始值恰好是'n'或'N'.
Also, you should write
char rep = 0;
instead, in case the original value of rep
happens to be 'n' or 'N'.
这篇关于Scanf 跳过扫描字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!