How to convert a string to integer in C?

后端 未结 12 1570
清酒与你
清酒与你 2020-11-22 01:40

I am trying to find out if there is an alternative way of converting string to integer in C.

I regularly pattern the following in my code.

char s[] =         


        
12条回答
  •  长发绾君心
    2020-11-22 01:59

    int atoi(const char* str){
        int num = 0;
        int i = 0;
        bool isNegetive = false;
        if(str[i] == '-'){
            isNegetive = true;
            i++;
        }
        while (str[i] && (str[i] >= '0' && str[i] <= '9')){
            num = num * 10 + (str[i] - '0');
            i++;
        }
        if(isNegetive) num = -1 * num;
        return num;
    }
    

提交回复
热议问题