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

cilk picture cilk · Oct 3, 2010 · Viewed 29.5k times · Source

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?

Answer

zserge picture zserge · Oct 3, 2010

You can use:

long int strtol(const char *nptr, char **endptr, int base);

Then check if *endptr != nptr. This means that the string at least begins with the integer. You can also check that *endptr points to terminating zero, which means that the whole string was successfully parsed.