我从书上复制了代码,这是一个像打击一样的循环,
for(;;)
{
printf("enter a value");
scanf("%lf",&value);
tot al+=value;
++count;
printf("do you want to enter another value?(N or Y):");
scanf("%c",&answer);
if(tolower(answer)=='n')
break;
}
但它有一些奇怪的行为,当我评估它时,它给出了输出
[tintin@tintin-laptop Documents]$ ./test
this enter a value3
do you want to enter another value?(N or Y):enter a value
我仔细检查了一下,终于什么时候改了
scanf("%c",&answer);
%c 之前有一个空格
scanf(" %c",&answer);
它的正常表现就像
[tintin@tintin-laptop Documents]$ ./test
this enter a value2
do you want to enter another value?(N or Y):y
enter a value3
do you want to enter another value?(N or Y):
为什么会发生这种事?
最佳答案
您被输入流中留下的换行符击中。
格式字符串中的前导空格将确保 scanf() 忽略所有空格。因此,后一个版本可以按预期工作。
您可以在scanf()的手册上找到此信息。 :
A directive composed of one or more white-space characters shall be executed by reading input until no more valid input can be read, or up to the first byte which is not a white-space character, which remains unread.
关于c 编程 scanf 有线行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19252531/