Results 1 to 5 of 5

Thread: Char or Number

  1. #1

    Thread Starter
    Member
    Join Date
    Dec 2002
    Location
    Miami,FL
    Posts
    34

    Char or Number

    How would u be able to find out if a person entered a number instead of a character and raise an error if they entered a character?

    For example u want the person to be able to enter only a number not a letter, how do u know if they entered a letter?

    thanks
    Death is always smiling down on us, the only thing we can do is smile back

  2. #2
    yay gay PT Exorcist's Avatar
    Join Date
    Apr 2002
    Location
    . . . my reason of shame
    Posts
    2,729
    if char's number is between 48 and 57 then it is a number..else it isnt
    \m/\m/

  3. #3
    yay gay PT Exorcist's Avatar
    Join Date
    Apr 2002
    Location
    . . . my reason of shame
    Posts
    2,729
    also c++ should have some string manip. library that has some isAlpha or isDigit function like all programming languages have
    \m/\m/

  4. #4

    Thread Starter
    Member
    Join Date
    Dec 2002
    Location
    Miami,FL
    Posts
    34
    so u have to store the number in a char data type?
    Death is always smiling down on us, the only thing we can do is smile back

  5. #5
    Kitten CornedBee's Avatar
    Join Date
    Aug 2001
    Location
    In a microchip!
    Posts
    11,594
    Several ways:
    C:
    1) Read in a string (fgets, scanf, ...) and check every character of the string for its number-being with isdigit from <ctype.h>.
    2) Read in an integer with scanf and check the return value. For example if you write
    int num;
    int read = scanf("%i", &num);
    and read is < 1 then the user didn't enter a number.

    C++:
    1) See C1, but using the locale-sensitive versions of the type functions. Either in <string> or in <locale>, not sure.

    2) cin fails if it doesn't read a number:
    int num;
    cin >> num;
    if(!cin.good())
    then something happened, most likely a format error. You can also set cin to throw an exception should such a thing occur.
    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