I am a new learner to c++, and right now going through the "Convert a string a an integer" problem. Following is my code, but when I tried it on Xcode, it printed 1068, which was not my expectation. I tried some others, the same bug just appeared. Anyone could help me about this?
#include <iostream> #include <string> using namespace std; int myAtoi(const char* str) { int Res=0; bool Sign=true; while(*str==' '){str++;} if(!isdigit(*str)&&*str!='+'&&*str!='-') {return 0;} if(*str=='+'||*str=='-'){ if(!isdigit(*(str+1))){return 0;} else if (*str=='-'){Sign=false;} str++; } while (isdigit(*str)){ if(Res>INT_MAX){return Sign?INT_MAX:INT_MIN;} Res=Res*10+int(*str+'0'); str++; } return Sign?Res:-Res; } int main(){ int sample=myAtoi(" +12"); cout<<sample<<endl; return 0; }
if(Res>INT_MAX)how do you expect this to happen?intcan become bigger thanINT_MAX? Do you know whatINT_MAXstands for?'0'from*strthan to add it. You'll still need to deal with the overflow before it happens, as others have indicated.