题目要求
写一个函数StrToInt实现将字符串转换为整数的功能。
注意的问题
- 字符串为空串或空指针.
- 字符串含有非0到9的字符.
- 特别注意字符串转换到int值,要考虑溢出的问题,正整数的最大值是0x7FFFFFFF (2147483647),负数的最小值是0x80000000(-2147483648).
#include <iostream>
#include <string.h>
using namespace std;
const int MAX = 2147483647;
const int MIN = -2147483648;
bool strToInt(const char *str,int &numInt)
{
numInt = 0;
if(str == NULL) {
std::cout<<"空指针"<<endl;
return false;
}
else if(str == "") {
cout<<"空串"<<endl;
return false;
}
else {
const char *p =str;
bool isFist = true;
bool hasMinus = false;
while(*p != '\0') {
if (isFist && *p == '-') {
hasMinus = true;
p++;
continue;
} else if (isFist && *p == '+') {
hasMinus = true;
p++;
continue;
}
if ((*p) >= '0' && (*p) <= '9') {
numInt = numInt*10 + *p-'0';
if( (!hasMinus && numInt > MAX/10) || (hasMinus && numInt < MIN/10) )
{
cout<<"存在整数溢出!"<<endl;
return false;
}
p++;
}
else {
cout<<"存在非法字符"<<endl;
return false;
}
}
if(hasMinus) {
numInt *= (-1);
}
return true;
}
}
int main() {
int numInt = 0;
char *str = NULL;
if(strToInt("123",numInt))
{
printf("%d\n",numInt);
}
if(strToInt("",numInt))
{
printf("%d\n",numInt);
}
if(strToInt(str,numInt))
{
printf("%d\n",numInt);
}
if(strToInt("+123",numInt))
{
printf("%d\n",numInt);
}
if(strToInt("-123",numInt))
{
printf("%d\n",numInt);
}
if(strToInt("-#45600@3#",numInt))
{
printf("%d\n",numInt);
}
if(strToInt("1004324230000000000000000000000000",numInt))
{
printf("%d\n",numInt);
}
if(strToInt("-100003424300000000000000000000000",numInt))
{
printf("%d\n",numInt);
}
return 0;
}