以下代码编译并按预期工作,尽管程序流程中有一个令人沮丧的错误,我不明白。
如果我传递2或5作为输入,主函数中间的循环工作正常。但是,当我传递-3或零以下的任何东西(例如返回-1的字符)时,循环会永远继续,程序甚至不会暂停为我提供scanf函数的输入。
#include <stdio.h>
#include <stdlib.h>
void getNum(char * prompt, int*num)
{
printf("%s", prompt);
scanf("%d", num);
}
int main(int argc, char ** argv)
{
int num = -1;
while(num < 0) { // problem here
getNum("Number of times you go to the gym in a week: ", &num);
}
return EXIT_SUCCESS;
}
我想知道错误是......
我注意到一些奇怪的事情......当我将循环更改为do-while循环时,它的工作正常......
int main(int argc, char ** argv)
{
int num;
do {
getNum("Number of times you go to the gym in a week: ", &num);
} while (num < 0); // this works fine ..
return EXIT_SUCCESS;
}
另外,出于某种原因,我重新编译了代码并且工作正常..
有人可以解释一下吗?
答案 0 :(得分:2)
接受回答后
scanf("%d", num);
,在读取非数字输入时,simple返回0,单独留下*num
。违规文本仍在stdin
中,后续调用将获得相同的文本和相同的结果。代码应检查scanf()
结果值。
// weak
scanf("%d", num); // fails to consume offending input.
// good
*num = 0; // default answer
int retval;
do {
printf("%s", prompt);
retval = scanf("%d", num); // returns EOF, 0, or 1
// consume rest of line
int c;
while ((c = fgetc(stdin)) != '\n' && c != EOF);
} while (retval == 0); // repeat is no number read and stdin still open
[编辑]
避免使用scanf()
。提供How to test input is sane作为妥善处理阅读int
的解决方案。
答案 1 :(得分:1)
尝试scanf
后,您可以尝试清除STDIN数据:
void getNum(char * prompt, int*num)
{
printf("%s", prompt);
scanf("%d", num);
// clean stdin
char c;
scanf("%c",&c);
while (c != '\n' && c != EOF) scanf("%c",&c);
}