Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determine if a C string is a valid int in C

Tags:

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?

like image 872
sara Avatar asked Mar 17 '12 20:03

sara


People also ask

How do I check if a string is valid?

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.


2 Answers

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.

like image 164
blueshift Avatar answered Sep 23 '22 06:09

blueshift


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.

like image 24
asveikau Avatar answered Sep 23 '22 06:09

asveikau