1. Limited time only! Sign up for a free 30min personal tutor trial with Chegg Tutors
    Dismiss Notice
Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Homework Help: Help with simplistic C code

  1. Oct 23, 2004 #1
    Hi, I am trying to write a loop that will check a users input to be between a certain numeric range in C. The thing is, I expect the person to enter a number, not a character.

    When the person enters a character, the loop becomes infinite. Thats the problem.
    If you look at example source code below:

    #include <stdlib.h>
    int main()
    int number=0;
    printf("input a number\n");
    scanf("%d", &number);
    while (number <1 || number >5)
    printf("incorrect number!!!!!\nput in new number");
    scanf("%d", &number);

    printf("\n your number is %d",number);
    printf("\n your number is: %d",number);
    return 0;

    it works fine for numbers, but if I enter letter 'a' for example, the loop becomes infinite.

    My question is, how do I go about the code such that a character that is inputted instead of a number prints error to screen and prompts user over again?

    I thought a statement like this while (number <1 || number >5) would do the trick, but it does not.
  2. jcsd
  3. Oct 23, 2004 #2
    check the ascii code of the user input. if it isn't in the range of values assigned to numbers, then print an error message.
  4. Oct 23, 2004 #3
    The problem is with the scanf argument. You should instead allow the user to enter an alphanumeric input and add a few lines to parse it and check if it is indeed a number (and not a spurious input).
  5. Oct 23, 2004 #4


    User Avatar
    Staff Emeritus
    Science Advisor
    Gold Member

    You should try to avoid using scanf entirely... in this case you're interested in a single digit, so getchar() would be simple to use.
Share this great discussion with others via Reddit, Google+, Twitter, or Facebook