2

我创建了一个函数来验证实数的输入。它运行良好,但由于atof()函数0在失败时返回,因此无法0作为输入值输入。任何人都可以帮助解决这个问题吗?

float validate_float()
{
    float num;
    char str[8];
    do
    {
        printf("enter a float number:");
        fflush(stdin);
        gets(str);
        num=atof(str);
    }
    while(num==0);
    return num;
}
4

3 回答 3

5

是的,这是atof().

您可以使用strtof()/strtod()代替。

语法:

double strtod(const char *nptr, char **endptr);
float strtof(const char *nptr, char **endptr);

注意:要区分实际输入 0无转换 0,您需要检查endptr.


既然如此,正如其他人所提到的,

  • 不要使用fflush(stdin). 它调用未定义的行为
  • 永远不要使用gets(),它可能会遭受缓冲区溢出。改为使用fgets()
于 2015-05-27T11:49:57.403 回答
1

这是众所周知的atof标准化限制。要规避此限制,strtod请改为使用并为第二个参数传递一个非空指针。

从我系统上的手册页:

双 strtod(const char *restrict nptr, char **restrict endptr);

…</p>

如果 endptr 不为 NULL,则指向转换中使用的最后一个字符之后的字符的指针存储在 endptr 引用的位置。

如果不执行转换,则返回零并将 nptr 的值存储在 endptr 引用的位置。

于 2015-05-27T11:50:36.810 回答
0
  1. 不要fflush() stdin这是未定义的行为。

  2. 很简单,就用这个

    int isfloat(const char *value)
     {
        char *endptr;
        float num; 
        num = strtof(str, &endptr);
        if (*endptr != '\0')
            return 0;
        return 1;
     }
    
于 2015-05-27T11:51:57.577 回答