-
isdigit woes
Im trying to use isdigit to invoke an error if a string has anything other than a digit in it and having no luck. My old code line will kick out something that starts with a non integer value, ex. e356, it will error but not error out with 3e56. I tried to utilize isdigit in place but I cant seem to get the syntax right. Am I even barking up the right tree trying to invoke isdigit for this kind of task?
Code:
#include <stdio.h>
#include <ctype.h>
// THIS IS BROKEN!!!!
#define MAXLINE 40
int main(void)
{
int error, n ;
char line[MAXLINE];
do {
printf("Input a positive integer: ");
fgets(line, MAXLINE, stdin);
//error = sscanf(line, "%d", &n) !=1 || n <= 0;// Old code
error = sscanf(line, "%d", &n) !=isdigit(n); //DOES NOT WORK
if(error)
printf("\nERROR: Do it again.\n");
}while(error);
printf("your line was: %s",line);
return 0;
}
-
What the hell is that line of code? isdigit() expects a single character, but you're passing it a pre-processed integer. Try something like this instead:
Code:
{
int i;
for(i = 0;line[i] && line[i] != '\n';++i)
if(!isdigit(line[i]))
printf("OOOO! %c is not a digit!\n", line[i]);
}
-
To be technically accurate, isdigit does in fact expect an int. However, the value is supposed to be that of a valid char, or EOF. So the call is valid C, it just won't do what they expect it to. :)
Quzah.
-
Notice that I said 'character' and not 'char'. I appreciate the clarification though. ;)