试图在C中理清用户输入错误

时间:2010-12-15 01:10:09

标签: user-input scanf

Hiya,我正在尝试制作一个小循环,当用户输入一个与浮动分开的东西并给他们另一个机会时会出现错误。这是我到目前为止所做的。

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

有人有任何想法吗?干杯球员

3 个答案:

答案 0 :(得分:1)

您没有在任何地方使用第二个scanf电话的返回值。所以它可能会成功,但是在输入已经被消耗之后,你会立即在循环的顶部再做一个scanf

答案 1 :(得分:1)

试试这个:

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

答案 2 :(得分:0)

我不确定行为是什么,但看起来你有一个额外的scanf()。作为while条件的一部分将在循环中每次重复。我认为在循环的底部不需要第二个。