1、itoa函数的用法
(1) 函数说明
itoa是广泛应用的非标准C语言扩展函数。由于它不是标准C语言函数,所以不能在所有的编译器中使用。但是,大多数的编译器(如Windows上
的)通常在<stdlib.h>头文件中包含这个函数。
功能:将任意类型的数字转换为字符串。在<stdlib.h>中与之有相反功能的函数是atoi。
(2) 函数原型
char *itoa(int value, char *string, int radix);
int value 被转换的整数,char *string 转换后储存的字符数组,int radix 转换进制数,如2,8,10,16 进制等。
头文件:
<stdlib.h>
(3)程序举例:
#include <stdlib.h>
#include <stdio.h>
int main()
{
int number = 123456;
char string[25];
itoa(number, string, 10);
printf("integer = %d string = %s\n", number, string);
return 0;
}
2、atoi函数的用法
C语言库函数名: atoi
功 能: 把字符串转换成整型数。
名字来源:ASCII to integer 的缩写。
原型: int atoi(const char *nptr);
函数说明: 参数nptr字符串,如果
第一个非空格字符存在,并且,如果不是数字也不是正负号则返回零,否则开始做类型转换,之后检测到非数字(包括结束符 \0) 字符时停止转换,返回整型数。
头文件: #include <
stdlib.h>
程序例:
1) #include <stdlib.h>
#include <stdio.h>
int main(void)
{
int n;
char *str = "12345.67";
n = atoi(str);
printf("string = %s integer = %d\n", str, n);
return 0;
}
执行结果:
string = 12345.67 integer = 12345
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