itoa是广泛应用的非标准C语言扩展函数。由于它不是标准
C语言函数,所以不能在所有的
编译器中使用。但是,大多数的
编译器(如Windows上的)通常在<stdlib.h>头文件中包含这个函数。功能:将任意类型的数字转换为字符串。在<stdlib.h>中与之有相反功能的函数是atoi
char *itoa(int value, char *string, int radix);
函数说明
参数nptr字符串,如果第一个非空格字符存在,是数字或者正负号则开始做类型转换,之后检测到非数字(包括结束符 \0) 字符时停止转换,返回整型数。否则,返回零,
头文件: #include <
stdlib.h>
程序例:
1)
#include <stdlib.h>
#include <stdio.h>
int main(void)
{
float n;
char *str = "12345.67";
n = atoi(str);
printf("string = %s integer = %f\n", str, n);
return 0;
}
执行结果:
string = 12345.67 integer = 12345.0
2)
#include <stdlib.h>
#include <stdio.h>
int main()
{
char a[] = "-100" ;
char b[] = "123" ;
int c ;
c = atoi( a ) + atoi( b ) ;
printf("c = %d\n", c) ;
return 0;
}
执行结果:
c = 23
简单的实现atoi函数
源代码:
#include <cctype>
int my_atoi(const char* p){
assert(p != NULL);
bool neg_flag = false;// 符号标记
int res = 0;// 结果
if(p[0] == '+' || p[0] == '-')
neg_flag = (*p++ != '+');
while(isdigit(*p)) res = res*10 + (*p++ - '0');
return neg_flag ?0 -res : res;
}