How does atoi() function in C++ work?

前端 未结 6 627
旧时难觅i
旧时难觅i 2020-12-15 20:07

So...I know that the atoi function in the C++ standard library is supposed to convert a string into an integer...how does it work?...(I\'m trying to learn stuff and I was ju

6条回答
  •  清酒与你
    2020-12-15 20:50

    Basically by subtracting ASCII zero ('0') and checking if it is a digit or not. You need to know the position:

    #include 
    #include 
    #include 
    
    int atoi( const char* nptr )
    {
        int result   = 0;
        int position = 1;
    
        const char* p = nptr;
        while( *p )
        {
            ++p;
        }
        for( --p; p >= nptr; p-- )
        {
            if( *p < 0x30 || *p > 0x39 )
            {
                break;
            }
            else
            {
                result += (position) * (*p - 0x30);
                position *= 10;
            }
        }
        result = ((nptr[0] == '-')? -result : result);
        return result;
    }
    
    int main()
    {
        char buffer[BUFSIZ] = {0};
    
        printf( "Enter an integer: " );
        fgets( buffer, BUFSIZ, stdin );
        buffer[strlen(buffer)-1] = 0;
    
        printf( "You entered %d\n", atoi( buffer ) );
    
        return 0;
    }
    

提交回复
热议问题