I need to check if a C string is a valid integer.
I tried both
int num=atoi(str);
and
int res=sscanf(str, "%d", &num);
But sending the string "8 -9 10"
in both of the lines returned simply 8, without indicating the invalidity of this string.
Can anyone suggest an alternative?
A string is called valid if the number of 0's equals the number of 1's and at any moment starting from the left of the string number 0's must be greater than or equals to the number of 1's.
Have a look at strtol(), it can tell you about invalid parts of the string by pointer return.
And beware of enthusiastic example code.. see the man page for comprehensive error-handling.
Maybe I'll get flamed for not using strtol
or similar libc
functions, but reasoning about this problem is not that hard:
#include <stdbool.h> // if using C99... for C++ leave this out.
#include <ctype.h>
bool is_valid_int(const char *str)
{
// Handle negative numbers.
//
if (*str == '-')
++str;
// Handle empty string or just "-".
//
if (!*str)
return false;
// Check for non-digit chars in the rest of the stirng.
//
while (*str)
{
if (!isdigit(*str))
return false;
else
++str;
}
return true;
}
[NB: I might have otherwise done isdigit(*str++)
instead of the else
to keep it shorter but my recollection is that the standards say it's possible that isdigit
is a macro.]
I guess one limitation is that this does not return false if the number in the string won't fit in an integer. That may or may not matter to you.
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