#include<iostream>
#include<string>
#include<limits>
using namespace std;
Bool Input = FALSE;
/************************************************
/* 将数字字符串转换成对应的整数
/************************************************/
int strToInt(const char* str)
{
Input = FALSE;
Bool IsMinus = FALSE;
const char* digit = str;
long result = 0;
if(NULL == str)
{
std::cerr<<"str is NULL"<<std::endl;
}
else if(NULL != str)
{
//判断首字符是不是正负号
if(*digit == '+')
{
digit++;
}
else if(*digit == '-')
{
IsMinus = TRUE;
digit++;
}
//判断剩下的字符
while(*digit != '\0')
{
//字符处于0-9之间的有效字符
if(*digit >= '0' && *digit <= '9')
{
result = result * 10 + (*digit - '0');
//溢出,即大于最大的正数,小于最小的负数
if((result > numeric_limits<int>::max() && !IsMinus) || (-result < numeric_limits<int>::min() && IsMinus))
{
result = 0;
break;
}
digit++;
}
//其他在0-9之外的非法字符
else
{
result = 0;
break;
}
}
//遍历到最后一个字符,说明是有效输入;检查正负号
if(*digit == '\0')
{
Input = TRUE;
if(IsMinus)
{
result = 0 - result;
}
}
}
return static_cast<int>(result);
}
int main()
{
cout<<"请输入你的字符串"<<endl;
char *mystring = new char[1024];
cin>>mystring;
cout<<"您所输入的字符串转换成整数为:"<<endl;
cout<<strToInt(mystring)<<endl;
cout<<"您的输入转换状态是:"<<endl;
cout<<Input<<endl;
delete[] mystring;
return 0;
}