atoi()函数
atoi()原型: int atoi(const char *str );
函数功能:把字符串转换成整型数。
参数str:要进行转换的字符串
返回值:每个函数返回 int 值,此值由将输入字符作为数字解析而生成。 如果该输入无法转换为该类型的值,则atoi的返回值为 0。
注意:使用该函数时要注意atoi返回的是int类型,注意输入str的范围不要超出int类型的范围。
一小段代码演示一下该函数的使用:
#include <stdio.h> #include <stdlib.h>
int main() { int a; char *ptr1 = "-12345"; a = atoi(ptr1); printf("a = %d,%d/n", a); return 0; }
下面来用C语言进行实现该函数:
#include <stdio.h> #include <stdbool.h>
int my_atoi(const char *src) { int s = 0; bool isMinus = false;
while(*src == ' ') //跳过空白符
{ src++; }
if(*src == '+' || *src == '-') { if(*src == '-') { isMinus = true; } src++; } else if(*src < '0' || *src > '9') //如果第一位既不是符号也不是数字,直接返回异常值 { s = 2147483647; return s; }
while(*src != '\0' && *src >= '0' && *src <= '9') { s = s * 10 + *src - '0'; src++; } return s * (isMinus ? -1 : 1); } int main() { int num;
char *str = "a123456"; num = my_atoi(str); printf("atoi num is: %d \r\n", num);
return 0; }
itoa()函数
itoa()原型: char *itoa( int value, char *string,int radix);
原型说明:
输入参数:
value:要转换的数据。
string:目标字符串的地址。
radix:转换后的进制数,可以是10进制、16进制等,范围必须在 2-36。
功能:将整数value 转换成字符串存入string 指向的内存空间 ,radix 为转换时所用基数(保存到字符串中的数据的进制基数)。
返回值:函数返回一个指向 str,无错误返回。
注意:itoa不是一个标准的c函数,他是windows特有的,跨平台写程序,要用sprintf。
1 #include <stdio.h>
2 #include <ctype.h>
3
4
5 //整数的各位数字加‘0’转换为char型并保存到字符数组中
6 int itoa(int n, char s[]) 7 { 8 int i; 9 int j; 10 int sign; 11
12 sign = n; //记录符号
13 if(sign < 0) 14 { 15 n = -n; //变为正数处理
16 } 17
18 i = 0; 19 do{ 20 s[i++] = n % 10 + '0'; //取下一个数字
21 }while((n /= 10) > 0); 22
23 if(sign < 0 ) 24 { 25 s[i++] = '-'; 26 s[i] = '\0'; 27 } 28
29 for(j = i; j >= 0; j-- ) 30 { 31 printf("%c \r\n", s[j]); 32 } 33 return 0; 34 } 36 int main() 37 { 38 int n; 39 char s[20]; 40
41 n = -688; 42 itoa(n, s); 43 return 0; 44 }
