strtol using errno

前端 未结 4 1927
有刺的猬
有刺的猬 2021-01-16 09:21

I have the following code:

#include 
#include 
#include 

void main(void)
{
     int data;
     char * tmp;
            


        
4条回答
  •  深忆病人
    2021-01-16 09:43

    strtol only sets errno for overflow conditions, not to indicate parsing failures. For that purpose, you have to check the value of the end pointer, but you need to store a pointer to the original string:

    char const * const str = "blah";
    char const * endptr;
    
    int n = strtol(str, &endptr, 0);
    
    if (endptr == str) { /* no conversion was performed */ }
    
    else if (*endptr == '\0') { /* the entire string was converted */ }
    
    else { /* the unconverted rest of the string starts at endptr */ }
    

    I think the only required error values are for underflow and overflow.

    Conversely, if the entire string has been consumed in the conversion, you have *endptr = '\0', which may be an additional thing you might want to check.

提交回复
热议问题