cstringtype-conversionstrtol

string to integer conversion edgecase handling


I want to convert a number, given in string format to an integer. I've found multiple solutions for this, like atoi() or strtol(). However, if not given an Input, that could be converted to an integer, like strtol("junk", &endptr, 10) I just get back the integer 0. This conflicts with cases, where I actually have the number "0" as my input.

Is there a function, that can handle this edgecase by returning a pointer to an integer, instead of an integer, so that in a case like above, I'd just get NULL?


Solution

  • If a conversion is successfully done, (eg, if value "0" is parsed), then the second parameter to strtol (endptr) will end up greater than the first one.

    If a conversion could not be done, then the parameter endptr will be unchanged.

    Demonstrated in this program:

    #include <stdio.h>
    
    int main(void) {
        char* text = "junk";
        char* endptr = NULL;
        
        int answer = strtol(text, &endptr, 10);
        
        if ( endptr > text )
        {
            printf("Number was converted: %d\n", answer);
        }
        else
        {
            printf("No Number could be found\n");
        }
    
        return 0;
    }