【发布时间】:2019-01-21 18:42:29
【问题描述】:
我正在尝试验证用户输入。 如果输入无效,我会尝试要求用户重新插入正确的数字(双精度)值。
程序不工作,进入无限循环。
您能给我一些建议吗?我该怎么做? 谢谢。!!
int main() {
double t; /* Input from user */
int check;
check = 0;
/* This loop is use to validate the user input. *
* For example: If the user insert a character value "x". *
* i am trying to ask the user to insert a valid numeric value. */
while (check == 0)
{
printf("Insert the value: ");
if (scanf(" %lf", &t) == 1) {
check = 1; /* Everythink okay. No loop needed */
}
else
{
printf("Failed to read double. ");
check = 0; /* loop aganin to read the value */
fflush( stdout );
}
}
return 0;
}
预期结果:
$ ./a.out
插入值:X
双读失败。
插入值:5
实际结果:
$ ./a.out
插入值:X
插入值:读取双倍失败。插入值:读取双倍失败。 (循环)...
【问题讨论】:
-
这个
X留在输入流中。您需要将其删除。考虑使用fgets并对其进行解析(例如使用sscanf)。
标签: c validation input scanf infinite-loop