字符串转整数

实现C++中atoi函数,字符串转整型

#include <iostream>
using namespace std;
int atoi_my(char* str){
    static const int MAX_INT = (int)((unsigned)~0 >> 1);
    int s;
    bool flag=true;
    while(*str==' '){
        ++str;
    }
    if(*str=='-'||*str=='+'){
        if(*str=='-'){
            flag=false;
        }
        ++str;
    }
    while(*str>='0'&&*str<='9'){
        if(s>MAX_INT/10){
            s=MAX_INT;
            break;
        }
        s=s*10+(*str-'0');
        ++str;
    }
    return s*(flag?1:-1);
}
int main() {
    char* c=new char[100];
    while(1){
        cin>>c;
        int ci=atoi_my(c);
        cout<<ci<<endl;
    }   
    return 0;
}

猜你喜欢

转载自blog.csdn.net/armstrong_rose/article/details/80461903