Results 1 to 7 of 7

Thread: Validate input numbers in C++

  1. #1
    omartalavera
    Guest

    Unhappy Validate input numbers in C++

    How validate input numbers in c++

    Example:

    int a;

    printf("Number: ");
    scanf("%i", &a);
    if (a is number) {
    }printf("a is number);
    else{
    printf("a is not a number);
    }


    in the sentence if ( ????? ) what to put ?

    Thanks!!

  2. #2
    Addicted Member
    Join Date
    Aug 2001
    Location
    I'm mobile
    Posts
    166
    I don't know if this helps you, but anyway, a header file, ctype.h/cctype.h includes several functions to determine if the input are numbers or not.....

    take a look at msdn for more info.

    To see if a is a number use
    is...(a)

    for example:

    if(isdigit(a))
    cout << a << " is a digit";


    hope this helps!
    [p r a e t o r i a n]

  3. #3
    omartalavera
    Guest

    Thanks!!!

    Thanks I help myself much!!!!!

  4. #4
    Addicted Member
    Join Date
    Aug 2001
    Location
    I'm mobile
    Posts
    166
    ok....
    [p r a e t o r i a n]

  5. #5
    Fanatic Member Wynd's Avatar
    Join Date
    Dec 2000
    Location
    In a bar frequented by colossal death robots
    Posts
    772
    Or you could try something like:
    PHP Code:
    char one '1'nine '9';

    if ((
    > (int)nine) || (< (int)one))
        
    printf("That is not a number\n"); 
    Those variables are there because I don't know the ASCII value of the characters. But, it should give you an idea.
    Alcohol & calculus don't mix.
    Never drink & derive.

  6. #6
    jim mcnamara
    Guest
    Most implementations of C, C++ have an is_numeric macro

    Here is one just for numbers, no + - or . chars:

    #define is_numeric(x) ((char)x >47 && (char)x < 58 )

    Code:
    int check_num(char *s){
      int i;
      char *buf;
      buf=s;
      for(;;){
           if(!is_numeric(*buf) return 0;  // handle null strings
           if(*buf==0x0) return 1;
           buf++;
      }
      // with well-formed string we should never get here
    }

  7. #7
    jim mcnamara
    Guest
    Most implementations of C, C++ have an is_numeric macro

    Here is one just for numbers, no + - or . chars:

    #define is_numeric(x) ((char)x >47 && (char)x < 58 )

    Code:
    int check_num(char *s){
      int i;
      char *buf;
      buf=s;
      for(;;){
           if(!is_numeric(*buf) return 0;  // handle null strings
           if(*buf==0x0) return 1;
           buf++;
      }
      // with well-formed string we should never get here
    }

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