在学习中总是遇到最终结果要靠字符数组或者字符串形式输出的情况。故在这里总结一下常用的方法:
(1)sprintf 和sscanf 一对函数
(2)gcvt(小数,有效长度,字符串),需要include<stdlib.h>,include <stdio.h>
(3)宏里的 #,只能将字面量转换成带“ ”的形式,
(4)atof,atoi,等一系列函数,将字符串(字符数组)型转换成数字型。
#include <stdio.h>
#include <stdlib.h>
#define STR(x) #x
#define STR1(x) STR(x)
int main()
{
float a=1234.12341233f;
char str[20];
sprintf(str,"%-15.3lf",a);//浮点数a转成str
printf("%s\n",str);
double db;
sscanf(str,"%lf",&db);// str转成浮点数,注意要传浮点地址
printf("%-15.3f\n",db);
char str2[20];
double num = 9.876;
gcvt(num,3,str2); //类似sprintf,将3位有效num转成str2
printf("%s\n",str2);
double db1 = 1.2345;
int i1 =4;
printf("%s\n",STR1(1.234));
printf("%s\n",STR(i1));//直接展开成“i1”
double db2 = atof(str2);//字符串转成浮点数
printf("%.3f\n",db2);
}