Saturday, January 14, 2012

Does a number string represents an integer or a floating value in C?

I got the shock of my blogging life when I cannot access an old post about the evils of the C function atof. Here is a code which return 1 for integers and 2 for floating point and 0 if not a valid integer or a valid float.

/*
author  Ernesto P. Adorio
        UPDEPP (University of the 
        Philippines, Extension Program
        in Pampanga, Clarkfield, Pampanga
email   ernesto. adorio@ gmail.com [remove spaces]
version 0.0.1 january 14, 2012
*/

#include 
#include 


int numbertype(char *s) 
{
   char *t = s;
   while (isspace(*t)) t++;
   if (*t == '\0') return 0;
    
   // number sign
   printf("ltrimmed [%s]", t);
   if (*t == '+' || *t == '-') t++;
   if (*t == '\0') return 0;
   printf("after sign [%s]", t);
   while (isdigit(*t)) t++;
   printf("after digits [%s]", t);
   if (*t == '\0') return 1; // an integer!
   
   // floating point??
   printf ("decimal point? [%s] ", t);  
   if (*t == '.') t++;
   printf ("fractional digits?");
   while (isdigit(*t)) t++;
   if (*t == '\0') return 2;
   
   // exponent part.
   printf ("testing exponent part %s", t); 
   if (*t == 'e') t++;
   printf ("after 'e' ");  
   if (*t == '\0') return 0; // error!
   printf ("sign after e?", t);  
   if (*t == '+' || *t == '-') t++;
   printf("%s", t);  
   if (*t == '\0') return 0; // error!
   while (isdigit(*t)) t++;
   if (*t == '\0') return 2; // a floating point number!
   return 0; // not an integer or floating point.
}

int main() 
{
  printf("numtype =[%d]", numbertype("-123.34")); 
};

Remove the deubgging printf statements when you use it for applications.

When the program is run, it returns a code of 2 to denote a floating point number, a 1 for an integer, and a 0 if not a number.


No comments:

Post a Comment