C语言 字符数组到浮点数转换
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15836866/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
character array to floating point conversion
提问by Vaibhav Sundriyal
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 = \n %s\n",buffer);
close(myfile);
}
return 0;
}
The sample output for this code is
此代码的示例输出是
Response = +1.29273072E-04
响应 = +1.29273072E-04
回答by Grijesh Chauhan
You may have two ways:
你可能有两种方法:
using double
atof(const char* str)float f; f = (float)atof(buffer); printf("%f",f); // here you can use fusing int
sscanf( const char * s, const char * format, ...)float f; sscanf(buffer,"%f",&f); printf("%f",f); // here you can use f
使用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 * 格式, ...)float f; sscanf(buffer,"%f",&f); printf("%f",f); // here you can use f

