字符串,整形数,浮点数之间的转换

时间:2022-12-12 17:50:46

一  字符串转化为整形数

//函数名:   atoi   
//功 能: 把字符串转换成整形数
//用 法: int atoi(const char *nptr);
//程序例:
#include <stdlib.h>
#include <stdio.h>

int main(void)
{
int n;
char *str = "12345.67 ";
n = atoi(str);
printf( "integer = %d\n ",n);
return 0;
}


二 字符串转化为浮点数

//函数名:   atof   
//功 能: 把字符串转换成浮点数
//用 法: int atof(const char *nptr);
//程序例:
#include <stdlib.h>
#include <stdio.h>

int main(void)
{
float n;
char *str = "12345.67 ";
n = atof(str);
printf( "integer = %f\n ",n);
return 0;
}

三 系列转化

#include   <stdlib.h> 
#include <stdio.h>

void main( void )
{
char *s; double x; int i; long l;

s = " -2309.12E-15 "; /* Test of atof */
x = atof( s );
printf( "atof test: ASCII string: %s\tfloat: %e\n ", s, x );

s = "7.8912654773d210 "; /* Test of atof */
x = atof( s );
printf( "atof test: ASCII string: %s\tfloat: %e\n ", s, x );

s = " -9885 pigs "; /* Test of atoi */
i = atoi( s );
printf( "atoi test: ASCII string: %s\t\tinteger: %d\n ", s, i );

s = "98854 dollars "; /* Test of atol */
l = atol( s );
printf( "atol test: ASCII string: %s\t\tlong: %ld\n ", s, l );
}