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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With