问题描述
在Stephen G. Kochan的书中,Programming in C有一个程序与
如下:
for(i = 1; i< = numOfGrades; ++ i){
printf(输入等级#%i:,i);
scanf(" i%"& grade);
。 ..
}
scanf命令是否暂停循环,直到收到用户输入?
运行此程序时循环继续运行而不会暂停
用户输入。
这里发生了什么?有人可以帮帮我吗?
JoshO。
In Stephen G. Kochan''s book "Programming in C" there is a program with the
following:
for(i = 1; i <= numOfGrades; ++i) {
printf("Enter grade #%i: ", i);
scanf("i%", &grade);
...
}
Does the scanf command pause the loop until the user input is received?
When I run this program the loop keeps on going without pausing for the
user input.
What is going on here? Can anyone please help me?
JoshO.
推荐答案
你好错了%i asi%。这意味着scanf()正在查找字母说明符后面的
字母,后面是NUL,这是非法的b $ b。在你的系统上它只是忽略它并返回。
当调用scanf()时你应该检查返回值,这会成功地给出
个字段转换,主要是为了防止坏用户输入b / b $ b,但也要发现这种错误。
Yoy''ve mistyped the "%i" as "i%". This means that scanf() is looking for the
letter I followed by the field specifier, followed by a NUL, which is
illegal. On your system it is simply ignoring it and returning.
When calling scanf() you should check the return value, which gives the
number of fields successfully converted, mainly to guard against bad user
input but also to catch this sort of error.
这篇关于在for循环中的scanf的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!