无法在c中进行字符串转换strtod

标签 c strtod

有人可以帮助我吗(抱歉英语),我试图将字符串转换为 double ,但是当我无法得到它时,这是我的代码(谢谢,我将非常感谢帮助):

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

#define MAX_LONG 5

char bx[MAX_LONG];
double cali=0;

int main() {
scanf("%c",bx);
cali = strtod(bx,NULL);
printf("%f",cali);
return 0;
}

当我在输出中输入大于 10 的值时,它只会打印第一个数字,如下所示:

 input: 23
 output: 2.00000
 input: 564
 output: 5.00000

最佳答案

您使用的 scanf() 说明符是错误的,除非您指定多个字符,但数组不会被 nul 终止,我建议如下

#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;
}

关于无法在c中进行字符串转换strtod,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29859010/

相关文章:

c - 在C中读取文件中的名称

C 在不同文件中定义的相同全局变量

c++ - 使用 std::strtod 后发生奇怪的事情

c - 获取字符串并转换为 double

c - memcpy 实现问题

c - 读取输入的txt文件并用c格式化

c - 小于 FLT_EPSILON 的最大数字是多少?

c++ - strtod 不会在错误输入时设置 errno

c - 在C中将字符串解析为 float

将 char * 转换为 double,而不会丢失 c 中的精度