can';t获取c中的字符串转换strod

can';t获取c中的字符串转换strod,c,strtod,C,Strtod,有人能帮我一下吗(对不起英语),我正在尝试将字符串转换为双精度,但当我无法得到它时,这是我的代码(谢谢,我非常感谢您的帮助): 您使用的scanf() #include <stdio.h> #include <string.h> #include <stdlib.h> int main() { char bx[6]; /* if you want 5 characters, need an array of 6

有人能帮我一下吗(对不起英语),我正在尝试将字符串转换为双精度,但当我无法得到它时,这是我的代码(谢谢,我非常感谢您的帮助):

您使用的
scanf()

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main() 
{
    char   bx[6]; /* if you want 5 characters, need an array of 6
                   * because a string needs a `nul' terminator byte
                   */
    double cali;
    char  *endptr;

    if (scanf("%5s", bx) != 1)
    {
        fprintf(stderr, "`scanf()' unexpected error.\n");
        return -1;
    }

    cali = strtod(bx, &endptr);
    if (*endptr != '\0')
    {
        fprintf(stderr, "cannot convert, `%s' to `double'\n", bx);
        return -1;
    }        
    printf("%f\n", cali);
    return 0;
}
#包括
#包括
#包括
int main()
{
char bx[6];/*如果需要5个字符,则需要一个6个字符的数组
*因为字符串需要一个'nul'终止符字节
*/
双卡利;
char*endptr;
如果(扫描频率(“%5s”,bx)!=1)
{
fprintf(stderr,“`scanf()”意外错误。\n”);
返回-1;
}
cali=strtod(bx和endptr);
如果(*endptr!='\0')
{
fprintf(stderr,“无法转换,`s'到`double'\n”,bx);
返回-1;
}        
printf(“%f\n”,cali);
返回0;
}

您应该尝试这些更改以使其正常工作

第一: 改变

为此:

scanf("%s",bx);/*Now you're reading a full string (No spaces)*/
cali = atof(bx);
第二: 改变

为此:

scanf("%s",bx);/*Now you're reading a full string (No spaces)*/
cali = atof(bx);

我认为这对你会很有效

非常感谢,我将在我的程序中实现这段代码(:这很好(我试图理解这是我的第一个程序)谢谢你需要阅读函数的手册或标准规范,以真正了解如何使用它们,例如
scanf()
在许多书中被误用。好吧,我会下载一个。我运行了代码,但它不起作用。请始终打印“`scanf()”意外错误:cw为什么不使用
scanf(“%lf”,&cali)
?您通常不希望阻止某人使用诸如
strtod
之类的功能,该功能在转换失败时提供远远优于
atof
的错误检查功能,后者提供……无。您希望帮助他们了解如何正确检查
errno
的结果,即
endptr
以及是否返回高/低无限值。
cali = strtod(bx,NULL);
cali = atof(bx);