源码:
#include<stdio.h>
#include<Windows.h>
#include<iostream>
#include<string>
#include<vector>
#include<assert.h>
using namespace std;
#pragma warning(disable:4996)
enum Status
{
ERR,
OK,
};
Status status = OK;
/*
字符串转换成整数,需要考虑以下几种情况:
1.字符串中包含空格
2.字符串中包含除数字字符外的其他字符
3.字符串中包含正负号
4.考虑整形数据的溢出问题
*/
int my_atoi(const char *str){
assert(str);
int flag = 1;//flag = 1 --> 正数 flag = -1 --> 负数
long long sum = 0;//防止溢出
//处理空格
while (isspace(*str)){
str++;
}
if ('\0' == *str){
status = ERR;
return 0;
}
//处理正负号
if ('-' == *str){
flag = -1;
str++;
}
else if ('+' == *str)
str++;
//字符串转整形
while (isdigit(*str)){
sum = sum * 10 + (flag*(*str - '0'));
//整形溢出
if (sum > INT_MAX || sum < INT_MIN){
status = ERR;
return -1;
}
str++;
}
if ('\0' == *str){
return (int)sum;
}
//字符串中包含其他字符
status = ERR;
return (int)sum;
}
int main(){
//char *str = "1234";
//char *str = "-1234";
//char *str = "-12345678923456776732874386582";
//char *str = "-12a34";
char *str = " ";
int ret = my_atoi(str);
if (OK == status){
cout << "success: " << ret << endl;
}
else{
cout << "failed: " << ret << endl;
}
system("pause");
return 0;
}
程序运行结果:
“1234”
带符号字符串:“-1234”
整形溢出:”-12345678923456776732874386582”
其他字符:”-12a34”
空字符串:“ ”