0

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; } 
4
  • 4
    if(Res>INT_MAX) how do you expect this to happen? Commented Oct 24, 2016 at 17:21
  • Yes you are right! I should have exchanged the position of this if condition and "Res=Res*10+int(*str-'0'); Commented Oct 24, 2016 at 21:00
  • So if you exchange those expressions you expect that variable of type int can become bigger than INT_MAX? Do you know what INT_MAX stands for? Commented Oct 24, 2016 at 21:30
  • It's probably more effective to subtract '0' from *str than to add it. You'll still need to deal with the overflow before it happens, as others have indicated. Commented Oct 25, 2016 at 15:03

1 Answer 1

3

You should be doing Res=Res*10+int(*str-'0'); instead of what you've done. *str is the character you're currently looking at. And to convert it into integer equivalent, you have to subtract the ASCII value of '0'.

It is quite intuitive that ASCII value of a digit n would be n + ASCII(0)

Sign up to request clarification or add additional context in comments.

2 Comments

Re: "It is quite intuitive" - even better, the C and C++ language definitions require that the character set have its digits contiguous and increasing. There's no need to assume that the encoding is ASCII.
Got it. Thank you very much!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.