[英]Program not reading the "double" input correctly
In this C program, if I enter b as the input, the program prints Enter correct input.在这个 C 程序中,如果我输入 b 作为输入,程序会打印 Enter correct input。 If I enter b45 as the input, the program again prints Enter correct input.
如果我输入 b45 作为输入,程序会再次打印 Enter correct input。 But, if I enter 45b, the program takes 45 as the input and proceeds normally.
但是,如果我输入 45b,程序将 45 作为输入并正常运行。
If I enter 45b, the program should print Enter correct input, but it is not happening.如果我输入 45b,程序应该打印输入正确的输入,但它没有发生。
#include <stdio.h>
int main()
{
double i;
printf ("Enter a number. \n");
while (scanf("%lf", &i) == 0)
{
printf("Enter correct input. \n");
fflush (stdin);
}
printf ("%lf\n", i);
return 0;
}
Instead of reading via scanf()
, read a line of user input with fgets(buf, ...)
, then use strtof(buf, &endptr))
to assess if the the input was numeric and endptr
to assess what is after the numeric text.不是通过
scanf()
读取,而是使用fgets(buf, ...)
读取一行用户输入,然后使用strtof(buf, &endptr))
评估输入是否为数字,并endptr
评估数字之后的内容文本。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.