Results 1 to 5 of 5

Thread: c integer checking

  1. #1

    Thread Starter
    Addicted Member
    Join Date
    Apr 2001
    Location
    Ottawa, Canada
    Posts
    181

    c integer checking

    hi

    i have a program where the user inputs an int. i wanna check if the int is valid, ie, no other characters besides numbers. i'm trying to get one character at a time from the int and check if 'isdigit()', but i'm not sure how to do this right or if there are alternatives...

    any help is appreciated.
    thank you
    --770

  2. #2
    Frenzied Member Technocrat's Avatar
    Join Date
    Jan 2000
    Location
    I live in the 1s and 0s of everyones data streams
    Posts
    1,024
    Here is some code that I made. I know there is a function some where, maybe the STL that will do this as well, but I always use mine.

    PHP Code:
    #define _ISDIGIT 0x10

    inline bool IsDigit(char *buf){return((*buf _ISDIGIT) ? : (*buf =='.'));} 
    MSVS 6, .NET & .NET 2003 Pro
    I HATE MSDN with .NET & .NET 2003!!!

    Check out my sites:
    http://www.filthyhands.com
    http://www.techno-coding.com


  3. #3

    Thread Starter
    Addicted Member
    Join Date
    Apr 2001
    Location
    Ottawa, Canada
    Posts
    181
    i'm new to c, so is there anything simple i could use? i think isdigit is in ctype.h, but it only accepts one digit at a time. how do i get one digit at a time from a big integer.

    also i don't understand your code, so i'm not sure how i can implemet it into mine..

    thanx though

    --770

  4. #4
    Frenzied Member
    Join Date
    Jul 2002
    Posts
    1,370
    You have to read string characters, then check if they are valid, then convert to int.
    Code:
    #include <ctype.h>
    char answer[10];
    char *buf;
    
    int number=0;
    memset(answer,0x00,sizeof(answer));
    
    while(1){
          printf("Enter a number: ");
          gets(answer);
          if(strlen(answer)){
          /* this next line reads thru the string looking only for digits */
            for(buf=answer;*buf && IsDigit(*buf);buf++);
            if (!*buf) break; /* if we read to the end of the stringit was okay */
          }
          printf("\nInvalid response. Please use numbers only\n");
    }
    number=atoi(answer);

  5. #5
    Kitten CornedBee's Avatar
    Join Date
    Aug 2001
    Location
    In a microchip!
    Posts
    11,594
    not
    gets(answer);
    but
    fgets(stdin, answer, 9);

    or you risk buffer overflows.
    All the buzzt
    CornedBee

    "Writing specifications is like writing a novel. Writing code is like writing poetry."
    - Anonymous, published by Raymond Chen

    Don't PM me with your problems, I scan most of the forums daily. If you do PM me, I will not answer your question.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width