|
-
Jan 18th, 2005, 05:48 AM
#1
Thread Starter
Addicted Member
is_numeric Function In C
Hello, I am trying to write a function where by you pass a character array to
my function and it will check to see if it is a valid number.
1) What is wrong with this code (if anything) ? and how do i use my function
2) Is their already such a function
Code:
int is_numeric(char input[256])
{
int c;
char ok = 1;
for(c = 0; &input[c] != "\0";c++)
{
if(input[c] < '0' && input[c] > '9')
{
ok = 1;
}
else
{
ok = 0;
}
if (ok == 0) return(NULL); else return(*input);
}
}
-
Jan 18th, 2005, 09:07 AM
#2
Not NoteMe
Re: is_numeric Function In C
Firstly, you declared your function to return an int, but you are actually returning a pointer. I suggest you return a 1 or a 0, as that i think would be most intuitive. Alternativly you could make the function return a pointer to char (char *).
Secondly, this line:
for(c = 0; &input[c] != "\0";c++)
has a problem. You're compareing the address of the ith element with a string. What you should do is change it to this:
for(c = 0; input[c] != '\0';c++)
Finally, because you've got your final if statement in your loop, as long as the first character is numeric it will return.
What you should do is remove the else return part, and at the end of the function assume that it's numeric (since there are no other characters in it).
Quotes:
"I am getting better then you guys.." NoteMe, on his leet english skills.
"And I am going to meat her again later on tonight." NoteMe
"I think you should change your name to QuoteMe" Shaggy Hiker, regarding NoteMe
"my sweet lord jesus. I've decided never to have breast implants" Tom Gibbons
Have I helped you? Please Rate my posts. 
-
Jan 19th, 2005, 08:48 AM
#3
Re: is_numeric Function In C
The comparison input[c] < '0' && input[c] > '9' is is not right, this expression is never true, you should use >='0' && <='9' if you mean "between 0 and 9".
While it is not an error, the ok variable is not needed here. You could simply use return statements:
Code:
int is_numeric(char input[256])
{
int c;
for(c = 0; input[c] != "\0";c++)
{
if(input[c] < '0' || input[c] > '9')
{
return 0;
}
}
return 1;
}
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|