Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c

casting

atoi

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?

like image 657
cilk Avatar asked Oct 03 '10 16:10

cilk


2 Answers

This does not cause stack overflow. atoi returns 0 if it can't find a number at the start of the string. Your (non-)handling of the 0 is what causes the stack overflow.

like image 86
Amadan Avatar answered Oct 07 '22 00:10

Amadan


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.

like image 20
zserge Avatar answered Oct 07 '22 00:10

zserge