字符数组到 float 的转换

标签 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. 使用 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
    

关于字符数组到 float 的转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15836866/

相关文章:

c - 规范化 2d c 数组列或行

c - 是否有预处理器指令在编译期间从标准输入读取源代码?

linux - 包含日志文件的 logrotate 目录

java - 方法调用中的 Null、原始数据值和包装类

c - 函数在 EditBox winApit 中获取选中的文本

c - 显式转换问题,C

java - 如何解压缩 lzo_deflate 文件?

linux - 为什么 "echo"没有出现在 "ps"中?

Scala:通配符(类型参数)和集合的编译错误: "you may wish to investigate a wildcard type as"

ios - Swift 3 中的十进制到 double 转换