把一个字符串转成整数:
StrToInt.cpp
#include <iostream>
using namespace std;
long long strToInt(const char* str)
{
long long num = 0;
bool minus = false;
cout << "befor To int :" << str << endl;
if(str != NULL && *str != '\0'){
if(*str == '+'){
str++;
minus = false;
}
if(*str == '-'){
str++;
minus = true;
}
while(*str != '\0'){
if(*str >= '0' && *str <='9'){
int flag = minus ? -1 : 1;
//核心语句就这句,其他都是健壮性处理
num = num*10 + flag*(*str - '0');
//是否超出范围
if((!minus && num >0x7FFFFFFF) || (minus && (signed int)num <0x80000000)){
num =0;
cout << "the range of number invalid! \n";
break;
}
str++;
}else{
num = 0;
cout << "the char of num invalid!\n";
break;
}
}
}
cout << "after to Int :" << num << endl;
return num;
}
int main(){
//测试
strToInt("123");
strToInt("-123");
strToInt("123aaa");
strToInt("");
strToInt("123456789");
strToInt("123999999999999999999999999999999999999");
return 0;
}
测试结果:
PC:~/algorithm$ g++ StrToInt.cpp -o StrToInt
PC:~/algorithm$ ./StrToInt
befor To int :123
after to Int :123
befor To int :-123
after to Int :-123
befor To int :123aaa
the char of num invalid!
after to Int :0
befor To int :
after to Int :0
befor To int :123456789
after to Int :123456789
befor To int :123999999999999999999999999999999999999
the range of number invalid!
after to Int :0