我正在尝试转换输出缓冲区(字符数组) 下面的代码转换为浮点格式以供进一步计算。 谁能告诉我怎么做。
#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
最佳答案
你可能有两种方式:
使用 double
atof
(const char* str)float f; f = (float)atof(buffer); printf("%f",f); // here you can use f
使用 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/