尝试解决C中的用户输入错误
你好,我正在尝试创建一个小循环,当用户输入除浮动之外的内容时会出现错误,并给他们另一个机会。这是我到目前为止所得到的。
printf("Enter a value for x: ");
while (scanf("%lf", &x_temp) != 1) {
printf("ERROR: Input real number\n");
printf("Enter a value for x: ");
scanf("%lf", &x_temp);
}
但这只是遍历循环,而没有给用户再次输入另一个数字的机会:
user@user-vm:~/Desktop/Exercise_0$ ./a.out
Enter a value for x: a
ERROR: Input real number
Enter a value for x: ERROR: Input real number
Enter a value for x: ERROR: Input real number
Enter a value for x: ERROR: Input real number
Enter a value for x: ERROR: Input real number
Enter a value for x: ERROR: Input real number
Enter a value for x: ERROR: Input real number
Enter a value for x: ERROR: Input real number
Enter a value for x: ERROR: Input real number
有人有什么想法吗?干杯,伙计们
Hiya, I'm trying to make a small loop which presents an error when the user inputs something apart from a float and gives them another opportunity. Here's what I've got so far.
printf("Enter a value for x: ");
while (scanf("%lf", &x_temp) != 1) {
printf("ERROR: Input real number\n");
printf("Enter a value for x: ");
scanf("%lf", &x_temp);
}
But this just runs through the loop without giving the user another chance to enter another number:
user@user-vm:~/Desktop/Exercise_0$ ./a.out
Enter a value for x: a
ERROR: Input real number
Enter a value for x: ERROR: Input real number
Enter a value for x: ERROR: Input real number
Enter a value for x: ERROR: Input real number
Enter a value for x: ERROR: Input real number
Enter a value for x: ERROR: Input real number
Enter a value for x: ERROR: Input real number
Enter a value for x: ERROR: Input real number
Enter a value for x: ERROR: Input real number
Anyone got any ideas? Cheers guys
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
试试这个:
Try this:
您没有在任何地方使用第二个
scanf
调用的返回值。所以它可能会成功,但是在输入被消耗之后,您立即在循环顶部执行另一个scanf
。You're not using the return value of the second
scanf
call anywhere. So it's probably succeeding, but then you immediately do anotherscanf
at the top of the loop, after the input has already been consumed.我不确定行为是什么,但看来您有一个额外的 scanf()。作为 while 条件一部分的条件将在每次循环中重复。我认为不需要在循环底部设置第二个。
I'm not sure what the behavior is, but it appears you have an extra scanf(). The one that is part of the while condition will repeat each time through the loop. I don't see a need for the second one at the bottom of the loop.