将字符串转换为整数产生的意外结果

时间:2016-10-24 17:12:20

标签: c++

我是c ++的新学习者,现在正在通过“将字符串转换为整数”问题。以下是我的代码,但是当我在Xcode上试用它时,它打印了1068,这不是我的期望。我尝试了其他一些,就出现了同样的错误。有人可以帮我这个吗?

#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;
}

1 个答案:

答案 0 :(得分:3)

你应该做Res=Res*10+int(*str-'0');而不是你做过的事。 *str是您当前正在关注的角色。要将其转换为等效的整数,您必须减去'0'的ASCII值。

数字n的ASCII值为n + ASCII(0)

非常直观