简单的C scanf函数不起作用? [英] Simple C scanf does not work?
问题描述
如果我尝试的东西,如:
If I try something such as:
int anint;
char achar;
printf("\nEnter any integer:");
scanf("%d", &anint);
printf("\nEnter any character:");
scanf("%c", &achar);
printf("\nHello\n");
printf("\nThe integer entered is %d\n", anint);
printf("\nThe char entered is %c\n", achar);
它允许输入一个整数,然后跳过第二个 scanf函数
彻底,这真是奇怪,因为当我交换两个(即字符
scanf函数第一),它工作正常。地球上有什么地方出错了?
It allows entering an integer, then skips the second scanf
completely, this is really strange, as when I swap the two (the char
scanf first), it works fine. What on earth could be wrong?
推荐答案
在使用 scanf函数
读输入,输入回车键后,读的是pressed但按返回键生成的新行不是由 scanf函数
消耗,这意味着未来你字符
从标准读取时间输入会有准备读一个换行符。
When reading input using scanf
, the input is read after the return key is pressed but the newline generated by the return key is not consumed by scanf
, which means the next time you read a char
from standard input there will be a newline ready to be read.
要避免的一种方法是使用与fgets
来读取输入一个字符串,然后提取你想用什么的sscanf
为:
One way to avoid is to use fgets
to read the input as a string and then extract what you want using sscanf
as:
char line[MAX];
printf("\nEnter any integer:");
if( fgets(line,MAX,stdin) && sscanf(line,"%d", &anint)!=1 )
anint=0;
printf("\nEnter any character:");
if( fgets(line,MAX,stdin) && sscanf(line,"%c", &achar)!=1 )
achar=0;
另一种方式来消耗换行符将 scanf函数(%C%* C,&安培; ANINT);
。在%* C
将读取缓冲区换行并将其丢弃。
Another way to consume the newline would be to scanf("%c%*c",&anint);
. The %*c
will read the newline from the buffer and discard it.
您可能需要阅读这一点:
You might want to read this:
这篇关于简单的C scanf函数不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!