Thread: isdigit woes

  1. #1
    Registered User
    Join Date
    Aug 2005
    Posts
    28

    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;
    }

  2. #2
    Gawking at stupidity
    Join Date
    Jul 2004
    Location
    Oregon, USA
    Posts
    3,218
    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]);
    }
    If you understand what you're doing, you're not learning anything.

  3. #3
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    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.
    Hope is the first step on the road to disappointment.

  4. #4
    Gawking at stupidity
    Join Date
    Jul 2004
    Location
    Oregon, USA
    Posts
    3,218
    Notice that I said 'character' and not 'char'. I appreciate the clarification though.
    If you understand what you're doing, you're not learning anything.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. isdigit() function
    By conor20_ie in forum C++ Programming
    Replies: 2
    Last Post: 04-17-2005, 02:25 PM
  2. isdigit()
    By kermit in forum C Programming
    Replies: 3
    Last Post: 03-19-2004, 09:59 PM
  3. I read the FAQ on isdigit() but...
    By CaptainJack in forum C Programming
    Replies: 5
    Last Post: 03-16-2004, 06:03 AM
  4. #include cctype and the isdigit
    By nextus in forum C++ Programming
    Replies: 2
    Last Post: 12-26-2002, 07:55 PM
  5. Correct use of isdigit
    By DocDroopy in forum C Programming
    Replies: 3
    Last Post: 08-05-2002, 07:22 AM