库函数原型:
#inclue <stdlib.h>
int atoi(const char *nptr);
用法:将字符串里的数字字符转化为整形数。返回整形值。
注意:转化时跳过前面的空格字符,直到遇上数字或正负符号才开始做转换,而再遇到非数字或字符串结束时('/0')才结束转换,并将结果返回。
例:
#include <stdio.h>
#include <stdlib.h>
int main()
{
char *ptr1 = "-12345.12";
char *ptr2 = "+1234w34";
char *ptr3 = " 456er12";
char *ptr4 = "789 123";
int a,b,c,d;
a = atoi(ptr1);
b = atoi(ptr2);
c = atoi(ptr3);
d = atoi(ptr4);
printf("a = %d, b = %d, c = %d, d = %d/n", a,b,c,d);
return 0;
}
输出结果:a = 12345, b = 1234, c = 456, d = 789
***************************************************
不调用库函数用C语言实现atoi函数的功能:
#include <stdio.h>
#include <stdlib.h>
int my_atoi(const char *str);
int main(int argc, char *argv[])
{
char *ptr = " 1234 3455";
int n;
n = my_atoi(ptr);
printf("myAtoi:%d/n", n);
n = atoi(ptr);
printf("atoi:%d/n", n);
return 0;
}
int my_atoi(const char *str)
{
int value = 0;
int flag = 1; //判断符号
while (*str == ' ') //跳过字符串前面的空格
{
str++;
}
if (*str == '-') //第一个字符若是‘-’,说明可能是负数
{
flag = 0;
str++;
}
else if (*str == '+') //第一个字符若是‘+’,说明可能是正数
{
flag = 1;
str++;
}//第一个字符若不是‘+’‘-’也不是数字字符,直接返回0
else if (*str >= '9' || *str <= '0')
{
return 0;
}
//当遇到非数字字符或遇到‘/0’时,结束转化
while (*str != '/0' && *str <= '9' && *str >= '0')
{
value = value * 10 + *str - '0'; //将数字字符转为对应的整形数
str++;
}
if (flag == 0) //负数的情况
{
value = -value;
}
return value;
}