字符数组到浮点转换

时间:2013-04-05 14:43:46

标签: c unix type-conversion

我正在尝试转换输出缓冲区(字符数组) 以下代码的浮点格式,以便进一步计算。 谁能告诉我怎么做。

#include "usbtmc.h"
#include <errno.h>
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
#include <getopt.h>
#include <inttypes.h>
#include <sys/types.h>
#include <pthread.h>

int main() 
{

    int myfile;
    char buffer[4000];

    int actual;

    myfile=open("/dev/usbtmc1",O_RDWR);
    if(myfile>0)
    {
        system("echo MEAS:VOLT:AC?>/dev/usbtmc1");
        actual=read(myfile,buffer,4000);

        buffer[actual] = 0;
        printf("Response = \n %s\n",buffer);

        close(myfile);
    }


    return 0;
}

此代码的示例输出为

响应=  + 1.29273072E-04

1 个答案:

答案 0 :(得分:5)

您可能有两种方式:

  1. 使用double atof(const char* str)

    float f;
    f = (float)atof(buffer);
    printf("%f",f); // here you can use f
    
  2. 使用int sscanf( const char * s, const char * format, ...)

    float f;
    sscanf(buffer,"%f",&f);
    printf("%f",f); // here you can use f