atoi函数
Hello, 大家好,我是一代,今天给大家讲解atoi函数的有关知识
所属专栏:C语言
创作不易,望得到各位佬们的互三呦
函数原型:int atoi (const char * str);
头文件:stdlib.h
功能:将字符串转换为整数。即跳过空白字符,碰到负号或者数字开始转换,转换到非数字字符为止。
注意:如果str中的第一个空白字符序列并不是有效的整数,或者由于str为空或仅包含空白字符而不存在这样的序列,则不执行转换并返回0.
转换成功后,函数将转换后的整数作为int值返回。
如果atoi()函数转换失败,例如要转换的类型超过了int表示的范围,如果要转换的是正数,则返回INT_MAX(2147483647),如果要转换的是负数,则返回INT_MIN(-2147483648)
#include<stdio.h>
#include<stdlib.h>
int main()
{
const char* str1 = " +";
const char* str2 = " 12er3";
const char* str3 = " -1239999999999";//超过了整形的最小值
const char* str4 = " \0+123";//碰到‘\0’结束
const char* str5 = "";
const char* str6 = "abc123";
const char* str7 = " \t+123";//‘\t’为一个字符
printf("%d ", atoi(str1));
printf("%d ", atoi(str2));
printf("%d ", atoi(str3));
printf("%d ", atoi(str4));
printf("%d ", atoi(str5));
printf("%d ", atoi(str6));
printf("%d ", atoi(str7));
return 0;
}
atoi函数模拟
#include<stdio.h>
#include<ctype.h>
int my_atoi(const char* str)
{
long long result = 0;//用long long 防止溢出
int flag = 1;
if (*str == '\0')
return 0;
while (isspace(*str))
{
str++;
}
if (*str == '-')
{
flag = -1;
str++;
}
if (*str == '+')
{
str++;
}
while (1)
{
if(isdigit(*str))//跳过空白字符
{
result = result * 10 + *str - '0';
}
else
{
return (int)result * flag;
}
if (result > _CRT_INT_MAX && flag == 1)
{
return _CRT_INT_MAX;
}
if (-result < -_CRT_INT_MAX - 1 && flag == -1)
{
return -_CRT_INT_MAX - 1;
}
str++;
}
return 0;
}
int main()
{
char str[100];
while (1)
{
gets(str);
int n = my_atoi(str);
if (n == -_CRT_INT_MAX - 1 || n == _CRT_INT_MAX)
{
printf("转换失败");
}
else
printf("转换成功:%d\n", n);
}
return 0;
}