How to check to ensure you have an integer before calling atoi()?

Viewed 34132

I wish to take an integer as a command line argument, but if the user passes a non-integer string, this will cause a stack overflow. What is the standard way to ensure atoi() will be successful?

9 Answers

To check for overflow, you can simply convert the number you got from atoi back to string. Now compare this string with your input string. If they match, then it's not an overflow, otherwise it is.

See a psuedo code here:

int check_overflow(int num, char *arr, int len){
    char buf[len + 1];
    sprintf(buf, "%d", num);
    if(strcmp(buf, arr) == 0){
            return 0;
    }
    return -1;
}

The function returns -1 if its an overflow else 0.

Related