简单的 C scanf 不起作用? [英] Simple C scanf does not work?
问题描述
如果我尝试诸如:
int anint;
char achar;
printf("
Enter any integer:");
scanf("%d", &anint);
printf("
Enter any character:");
scanf("%c", &achar);
printf("
Hello
");
printf("
The integer entered is %d
", anint);
printf("
The char entered is %c
", achar);
它允许输入一个整数,然后完全跳过第二个 scanf
,这真的很奇怪,因为当我交换两个时(首先是 char
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
读取输入时,按下回车键后读取输入但不回车键生成的换行符scanf
使用,这意味着下次从标准输入读取 char
时,将有一个新行可供读取.
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("
Enter any integer:");
if( fgets(line,MAX,stdin) && sscanf(line,"%d", &anint)!=1 )
anint=0;
printf("
Enter 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屋!