atol() v/s. strtol()

前端 未结 7 1771
伪装坚强ぢ
伪装坚强ぢ 2020-11-30 19:13

What is the difference between atol() & strtol()?

According to their man pages, they seem to have the same effect as well as matching arguments:

         


        
7条回答
  •  失恋的感觉
    2020-11-30 20:11

    The man page of strtol gives the following:

    ERRORS
       EINVAL (not in C99) The given base contains an unsupported value.
       ERANGE The resulting value was out of range.
       The implementation may also set errno to EINVAL in case no conversion was performed (no digits seen, and 0 returned).
    

    The following code checks for range errors. (Modified Eli's code a bit)

    #include 
    #include 
    #include 
    #include 
    
    int main()
    {
       errno = 0;
       char* end = 0;
       long res = strtol("83459299999999999K997", &end, 10);
    
       if(errno != 0)
       {
          printf("Conversion error, %s\n", strerror(errno));
       }
       else if (*end)
       {
          printf("Converted partially: %i, non-convertible part: %s\n", res, end);
       }
       else
       {
          printf("Converted successfully: %i\n", res);
       }
    
       return 0;
    }
    

提交回复
热议问题