C: Check if string is a number

By Eric Downing. Filed in C/C++, Programming  |  
TOP del.icio.us digg

I was recently testing some basic input and wrote this code to test if the input was a number or not.

#include 

int main()
{
  char name[10];

  scanf("%s",&name);
  if (checkifNumber(name))
  {
     printf("Is a numbern"); 
  }
  else
  {
     printf("Invalid numbern");
  }
}

int checkifNumber(char *inp)
{
  int i=0;
  int isanumber = 1;

  while(inp[i] != '' && i < 10)
  {
    if (inp[i] >= '0' && inp[i] <= '9')
    {
    }
    else
    {
      isanumber =0;
    }
    i++;
  }
  return isanumber;
}

One thing that could be improved is to potentially use a global variable to define the length of the
input string as it is used in two different places in the program and could potentially lead to an
array overrun/underrun.

Tags: ,

Leave a Reply