实现:
/********************************** 字符串转整数 by Rowandjj 2014/7/15 ***********************************/ #include<iostream> #include<stdlib.h>//不加这个头文件在九度oj上会编译错误 using namespace std; int state = 0;//0代表串非法,1代表正常 long Str2Int(const char *str) { long num = 0; if(str == NULL)//输入null { state = 0; return 0; } const char* digit = str; int minius = 0;//0代表正数,1代表负数 while(*digit == ' ')//跳过空格 { digit++; } if(*digit == '+') { digit++; } else if(*digit == '-') { minius = 1; digit++; } if(*digit == '\0')//只输入+或者- { state = 0; return 0; } while(*digit != '\0') { if(*digit > '9' || *digit < '0')//非法字符 { state = 0; return 0; } state = 1; num = num*10 + (*digit - '0');//核心代码 digit++; } //越界 if(*digit>0x7fffffff || *digit<(signed int)0x80000000) { state = 0; return 0; } return minius?(0-num) : num; } int main() { long digit; char str[1000]; char *p = str; while(cin>>p) { digit = Str2Int(p); if(state==0) { cout<<"My God\n"; }else//state == 1 { cout<<digit<<endl; } } return 0; }
原文地址:http://blog.csdn.net/chdjj/article/details/37810659