Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
747 views
in Technique[技术] by (71.8m points)

c - character array to floating point conversion

I am trying to convert the output buffer(character array) of the code below to floating point format for further calculations. Can anybody tell me how to do it.

#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 = 
 %s
",buffer);

        close(myfile);
    }


    return 0;
}

The sample output for this code is

Response = +1.29273072E-04

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You may have two ways:

  1. using double atof(const char* str)

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

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...