char型字符串转换为整型的数,当然只能限定字符串存放的是'0'~'9'型的字符,一般使用atoi函数:
#include <stdlib.h>
int atoi(const char *nptr); //转换之后就是整型的数
而整型,浮点型的数转换为字符串时会有两种方法:一种是用函数实现,一种则是格式输出;函数实现的方法相对繁琐,可以用到itoa()函数,但是该函数不能被移植,而推荐另一种方式--格式输出:
#include <stdio.h>
int sprintf(char *str, const char *format, ...);
int snprintf(char *str, size_t size, const char *format, ...);
上述的两种方法实现相对简单:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char buf[20];
double pi = 3.1415926;
memset(buf, 0, sizeof(buf));
sprintf(buf, "%.7lf", pi); //浮点型数据默认只写小数点后6位,这里指定写入的位数
printf("%s\n", buf);
return 0;
}
这种方法使得一个浮点型数据可以转换为字符串,而snprintf()则是需要加上写入buf中浮点型数据的字节数。