How to convert a string to integer in C?

后端 未结 12 1565
清酒与你
清酒与你 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:47

    You can always roll your own!

    #include 
    #include 
    #include 
    
    int my_atoi(const char* snum)
    {
        int idx, strIdx = 0, accum = 0, numIsNeg = 0;
        const unsigned int NUMLEN = (int)strlen(snum);
    
        /* Check if negative number and flag it. */
        if(snum[0] == 0x2d)
            numIsNeg = 1;
    
        for(idx = NUMLEN - 1; idx >= 0; idx--)
        {
            /* Only process numbers from 0 through 9. */
            if(snum[strIdx] >= 0x30 && snum[strIdx] <= 0x39)
                accum += (snum[strIdx] - 0x30) * pow(10, idx);
    
            strIdx++;
        }
    
        /* Check flag to see if originally passed -ve number and convert result if so. */
        if(!numIsNeg)
            return accum;
        else
            return accum * -1;
    }
    
    int main()
    {
        /* Tests... */
        printf("Returned number is: %d\n", my_atoi("34574"));
        printf("Returned number is: %d\n", my_atoi("-23"));
    
        return 0;
    }
    

    This will do what you want without clutter.

提交回复
热议问题