目录
1.atoi函数
头文件 #include<stdlib.h>
atoi函数的声明 int atoi(const char *str)
atoi函数是将参数str所指向的字符串转换为一个整数(int型)。
1.1 atoi函数的实现
#include <stdlib.h>
int main()
{
int a = 0;
char str[20] = "1234";
a=atoi(str);
printf("%d\n", a);
return 0;
}
2. atoi函数的模拟实现
#include<assert.h>
#include<ctype.h>
#include <stdlib.h>
enum Status
{
VALID,
INVALID
}status=INVALID;//非法
int my_atoi(const char* str)
{
int flag = 1;
//空指针
assert(str);
//字符串为空
if (*str == '\0')
{
return 0;//
}
//空白字符
while (isspace(*str))
{
str++;
}
//正负号
if (*str == '+')
{
flag = 1;
str++;
}
if (*str == '-')
{
flag = -1;
str++;
}
long long n = 0;
while (*str != '\0')
{
if (isdigit(*str))
{
n = n * 10 + flag * (*str - '0');
if (n<INT_MIN || n>INT_MAX)
{
n = 0;
break;
}
}
else
{
break;
}
str++;
}
if (*str == '\0')
{
status = VALID;
}
return (int)n;
}
int main()
{
char arr[20] = " -1234";
int ret = my_atoi(arr);
if (status == VALID)
printf("正常转化 %d\n", ret);
else
printf("非法转化 %d\n", ret);
printf("%d\n", ret);
return 0;
}
模拟实现结果如下
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/119598.html