#include <iostream>
#include <limits>
using namespace std;
enum status
{
Valid = 0,
Invalid
};
int g_status = Valid;
int StrToInt(const char *str)
{
g_status = Invalid;
long long num = 0;
if(str != NULL)
{
const char *digit = str;
//第一个字母是加减号吗?
bool minus = false;
if(*digit == '+')
{
digit++;
}
else if(*digit == '-')
{
digit++;
minus = true;
}
while(*digit != '\0')
{
if(*digit >= '0' && *digit <= '9')
{
num = num*10 + (*digit - '0');
if(num > std::numeric_limits<int>::max())
{
num = 0;
break;
}
digit++;
}
else
{
num = 0;
break;
}
}
if(*digit == '\0')
{
g_status = Valid;
if(minus)
{
num = -num;
}
}
}
return static_cast<int>(num);
}
void main()
{
const char *s = "-1234";
int a = StrToInt(s);
cout << a << endl;
}
//这里有几点需要多加思考:
//1//非法输入,指针判空。
//2//大数溢出
//3//空指针和合法的0怎么区别
【100题】String TO Int
最新推荐文章于 2023-09-16 10:45:43 发布