c - 如何检查用户输入是否是 C 中的 float ?

标签 c

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

#include <stdio.h>

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 <stdio.h>
#include <stdlib.h>
#include <ctype.h>
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");
} 

关于c - 如何检查用户输入是否是 C 中的 float ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33621681/

相关文章:

c - 调试断言失败! (不正常)

C - 每个服务器线程为许多客户提供服务

c - C中通过指针将函数的返回值传递给另一个函数

c - if..else..if..else 代码无法正常工作(用 C 语言编码)

c - 执行 typedef 时初始化结构数组

c - 在 xCode 中读取 C 错误

c - libxml2 和 XPath 在 ANSI C 中遍历 child 和 sibling

c++ - 指针对象的指针变量的语法如何工作?

c++ - 无法在 ubuntu 12.04 64 位中使用 gloox 库

c - 如何在 unix 中跟踪文件修改?