如何检查用户输入是否是C中的浮点数?

我正在尝试创建一个程序,检查用户输入的数字是否为浮点数,但它不起作用。 我尝试用scanf检查,但这也不起作用。

 #include  int main(void) { float num1; printf("enter number: "); scanf("%lf", &num1); if (scanf("%lf")) { printf("Good \n"); } else { printf("Bad \n"); } } 

您是否阅读过有关scanf(3)任何文档?

您需要像这样检查返回值

 double value; if (scanf("%lf", &value) == 1) printf("It's float: %f\n", value); else printf("It's NOT float ... \n"); 

有一种我更喜欢的方式,因为它可以对后续输入提供更多控制, scanf()很少有用。 而是尝试fgets()

 #include  #include  #include  int main(void) { char buffer[100]; double value; char *endptr; if (fgets(buffer, sizeof(buffer) stdin) == NULL) return -1; /* Unexpected error */ value = strtod(buffer, &endptr); if ((*endptr == '\0') || (isspace(*endptr) != 0)) printf("It's float: %f\n", value); else printf("It's NOT float ...\n"); } 

测试字符串是否转换为double的最佳方法是使用strtod()

strtod()可能很难使用。 使用strtod(char *s, char *endptr) ,如果s == endptr ,则转换失败。 否则检查从endptr开始的字符串endptr有违规字符。

这里没有解决溢出/下溢问题,除了说strtod()和转换为float将很容易转换为零或无穷大 – 两者通常可以表示为float

 #include  #include  #include  bool is_float(const char *s, float *dest) { if (s == NULL) { return false; } char *endptr; *dest = (float) strtod(s, &endptr); if (s == endptr) { return false; // no conversion; } // Look at trailing text while (isspace((unsigned char ) *endptr)) endptr++; return *endptr == '\0'; } void is_float_test(const char *s) { float x; printf("Test(\"%s\"):\n", s ? s : "NULL"); if (is_float(s, &x)) { printf("Good (float) %e\n", x); } else { puts("Bad (float)"); } } int main(void) { // Test cases is_float_test("123"); is_float_test(" 123"); is_float_test("123.456\n"); is_float_test("123 "); is_float_test("123e123"); is_float_test("123e456"); is_float_test(" 123 xyz"); is_float_test(" abc"); is_float_test(" "); is_float_test(""); // Chance for user input char buffer[80]; is_float_test(fgets(buffer, sizeof buffer, stdin)); return 0; } 

产量

 Test("123"): Good (float) 1.230000e+02 Test(" 123"): Good (float) 1.230000e+02 Test("123.456 "): Good (float) 1.234560e+02 Test("123 "): Good (float) 1.230000e+02 Test("123e123"): Good (float) inf Test("123e456"): Good (float) inf Test(" 123 xyz"): Bad (float) Test(" abc"): Bad (float) Test(" "): Bad (float) Test(""): Bad (float)