简体   繁体   English

将字符串转换为浮点数在C中?

[英]Converting string to float in C?

Right, So in my C program i have a function that takes a float value from file, and here i am trying to do the reverse, taking the string and turning it into a float. 是的,所以在我的C程序中,我有一个从文件中获取浮点值的函数,在这里我试图做相反的事情,将字符串转换为浮点数。

 float PsSc = atoi(stock01[DataCount].defPsSc);

I know my error, i assumed it would work for both integers and floats, it doesn't. 我知道我的错误,我以为它适用于整数和浮点数,但事实并非如此。

I have tried 我努力了

 float PsSc = atof(stock01[DataCount].defPsSc);

and that doesn't work either. 那也不行。

So, My question is: What can i replace my current line of code with to make it work? 因此,我的问题是:我可以用什么替换当前的代码行使其起作用?

Input: 1.45 . 输入:1.45。 Expected output: 1.45, Real output: 1.00 预期输出:1.45,实际输出:1.00

Edit: 编辑:

 printf("\nYour previous speed was : %.2f Metres per Second",PsSc);

The strtod() function family is what you are looking for. 您正在寻找strtod()函数族。

Not only will strtod() convert the input string to a double (with strtof() for float and strtold() for long double ), it also tells you exactly where it stopped parsing the input string (through the second parameter). 不仅将strtod()输入字符串转换为double (与strtof()floatstrtold()long double ),它也告诉你究竟在何处停止解析输入字符串(通过第二个参数)。

Note that it is locale-dependent whether either strtod() or atof() expect a decimal point or a decimal comma ... 需要注意的是区域设置相关的或者是否strtod()atof()期待一个小数点或小数逗号 ......

#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <errno.h>

#include <stdio.h>

int main()
{
    // play with "." vs. "," to see why this might be your problem
    char * input = "1.45";

    // will take a pointer beyond the last character parsed
    char * end_ptr;

    // strto...() might give an error
    errno = 0;

    // convert
    float result = strtof( input, &end_ptr );

    if ( errno == ERANGE )
    {
        // handle out-of-range error - result will be HUGE_VALF
        puts( "out of range" );
    }

    if ( end_ptr != ( input + strlen( input ) ) )
    {
        // handle incomplete parse
        printf( "Unparsed: '%s'\n", end_ptr );
    }

    printf( "result: %.2f\n", result );
    return 0;
}

Why we shouldn't use atof 为什么我们不应该使用atof

On success, atof() function returns the converted floating point number as a double value. 成功时,atof()函数将转换后的浮点数作为双精度值返回。 If no valid conversion could be performed, the function returns zero (0.0). 如果无法执行有效的转换,则该函数将返回零(0.0)。 If the converted value would be out of the range of representable values by a double, it causes undefined behavior . 如果转换后的值超出可表示值范围的两倍,则将导致未定义的行为

instead we should use strtod() present in <stdlib.h> 相反,我们应该使用<stdlib.h>存在的strtod()

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
int main()
{
    char s[] = "1.45";
    printf("Float value : %4.2f\n",strtod(s,NULL));
    return 0;
}

it will correctly prints 1.45 它将正确打印1.45

See the illustration here http://ideone.com/poalgY 请参阅此处的插图http://ideone.com/poalgY

Try using sscanf which is much more specific: 尝试使用更具体的sscanf

Reference : http://www.cplusplus.com/reference/cstdio/sscanf/ 参考: http : //www.cplusplus.com/reference/cstdio/sscanf/

float PsSc;

sscanf(stock01[DataCount].defPsSc, "%f", &PsSc);

Example : http://ideone.com/BaPmDj 范例: http//ideone.com/BaPmDj

#include <stdio.h>

int main(void) {
    char * str = "1.45";

    float flt;

    sscanf(str, "%f", &flt);

    printf("value = %f\n", flt);

    return 0;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM