尝试解决C中的用户输入错误

发布于 2024-10-07 11:50:18 字数 847 浏览 5 评论 0原文

你好,我正在尝试创建一个小循环,当用户输入除浮动之外的内容时会出现错误,并给他们另一个机会。这是我到目前为止所得到的。

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

極樂鬼 2024-10-14 11:50:18

试试这个:

for (;;)
{
    printf("Enter a value for x:   ");
    if (scanf("%lf", &x_temp) == 1) 
        break;
    printf("ERROR: Input real number\n");
}

Try this:

for (;;)
{
    printf("Enter a value for x:   ");
    if (scanf("%lf", &x_temp) == 1) 
        break;
    printf("ERROR: Input real number\n");
}
优雅的叶子 2024-10-14 11:50:18

您没有在任何地方使用第二个 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 another scanf at the top of the loop, after the input has already been consumed.

流心雨 2024-10-14 11:50:18

我不确定行为是什么,但看来您有一个额外的 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文