Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading