checking string if number or not
I've made a function that determines if character string is a number or not.Using only isdigit().
Here is my sample code
Code:
#include <string.h>
#include <stdio.h>
#include <ctype.h>
int isNumber(char str[])
{
int withDecimal =0,isNegative=0 ,i=0;
int len = strlen(str);
for (i=0; i<len; i++)
{
if (!isdigit(str[i])) // if1
{
if (str[i] == '.')
{
if(withDecimal){
return 0;
}
withDecimal =1;
}
else if (str[i] == '-')
{
if(isNegative){
return 0;
}
if(i==0){
isNegative = 1;
}else{
return 0;
}
}else{
return 0;
}
} //end if1
}// end for
return 1;
}
int main(){
//for testing purpose only
char charNum[10][15] = {
"100.23" ,
"-200.456",
"200..",
"..200",
"4.9.9.6",
"--500",
"500--",
"59-52-6",
"50.69-5",
"5000"
};
int cntr = 0;
for(cntr=0; cntr<10; cntr++){
printf("%s\t\t", charNum[cntr]);
if(isNumber(charNum[cntr])){
printf("is a number!\n");
}else{
printf("NOT a NUMBER!\n");
}
}
}
and here is the output
Code:
100.23 is a number!
-200.456 is a number!
200.. NOT a NUMBER!
..200 NOT a NUMBER!
4.9.9.6 NOT a NUMBER!
--500 NOT a NUMBER!
500-- NOT a NUMBER!
59-52-6 NOT a NUMBER!
50.69-5 NOT a NUMBER!
5000 is a number!
as you can see. The function works fine.But to be on the safe side.I need to know your reaction on the function, whether it needs to improve on some aspects (memory utilization or something).
regards,
Jaro