atoi函数
atoi函数是把字符串转换成整型数的一个函数,应用在计算机程序和办公软件中。int atoi(const char *nptr) 函数会扫描参数 nptr字符串,跳过前面的空白字符(例如空格,tab缩进)等,可以通过isspace( )函数来检测),直到遇上数字或正负符号才开始做转换,而在遇到非数字或字符串结束符(‘\0’)才结束转换,并将结果返回。如果 nptr不能转换成 int 或者 nptr为空字符串,那么将返回 0 。
#include <stdlib.h>
#include <stdio.h>
int main(void)
{
int n;
char *str = "12345";
n = atoi(str);
printf("n=%d\n",n);
return 0;
}
输出n=123456
模拟实现atoi
代码实现:
#include<stdio.h>
int StrToInt(char *str)
{
long number = 0;
int flag = 1; //判断符号位
if (NULL == str)
{
printf("str is NULL");
return 0;
}
while (*str == ' ') //空格
{
str++;
}
if (*str == '-') //符号位
{
flag = -1;
str++; //后移3移位
}
while ((*str >= '0') && (*str <= '9'))//转化
{
number = number * 10 + *str - '0';
str++;
}
return flag*number;
}
int main()
{
char* str = "-123456";
int tmp = StrToInt(str);
cout << tmp;
}