I am taking a string input from user. But how d I check whether user has entered a string or a number??
Call strtol, check that the value stored to endptr is not equal to the input (successful conversion), and is a pointer to a NUL byte (the whole string was used).
http://www.opengroup.org/onlinepubs/000095399/functions/strtol.html
explains that if you also want to detect overflow, the trick is to set errno to 0, then call strtol, then check that errno is still 0.
If you want to be pedantic, you also have to check using isspace() that the first character of the input string is a non-space. The reason is that strtol and friends skip over initial whitespace, but perhaps you don't consider " 1" to be a valid number.
Alternatives include strtoll and strtod, respectively if you want to allow bigger numbers, or non-integer numbers.
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