0

part of the program that i am working on is to get a number from the user , but the condition is that it has to be any number between 1 and 10 nothing else, so how could i force the user to only input one of these specific numbers , so that if he wrote any other number or a character , an error message to pop out and repeat the process till he choses correctly

here is the code

    // getting a number from the user

    int number;
    printf("Please pick a number from 1 to 10 : ");
    scanf("%d",&number);
    printf("Oh ! You have chosen %d\n", number);


    // what should i do here ?
Barmar
  • 741,623
  • 53
  • 500
  • 612
  • 1
    Use a loop to repeat the question, and an `if` statement to test if the number is between 1 and 10. If it is, break out of the loop. – Barmar Jul 20 '21 at 06:41
  • 1
    There's more to it than this but if the user enters a number outside that range do you know how to write a condition to check for that? Take small steps. – kaylum Jul 20 '21 at 06:41
  • 1
    You can't use `%d` format if you need to check for non-numeric input. – Barmar Jul 20 '21 at 06:43
  • 2
    See https://stackoverflow.com/questions/31633005/validate-the-type-of-input-in-a-do-while-loop-c for how to check if it's a number. – Barmar Jul 20 '21 at 06:46
  • 1
    @Barmar that's not true. scanf will return with an error if it's unable to parse a numeric input (when non-numeric input was given). OP might and should also check for that. – paladin Jul 20 '21 at 07:09
  • 2
    @paladin But once that happens, you're stuck, you can't call `scanf()` again, it will just try to read the same thing. This is why you should use `fgets()` to read a line of input, and then use `sscanf()` to parse it. – Barmar Jul 20 '21 at 07:12
  • @Barmar or use one of the upvoted answers – Jabberwocky Jul 20 '21 at 07:36

4 Answers4

1

C allows for very nice input control, but it is not free... Said differently you cannot rely on the language nor on the standard library but have to code everything by hand.

What you want:

  1. control that the input is numeric
  2. control that the number lies between 1 and 10

How to:

  1. control the return value of the input function
  2. if you got a number control its value
  3. if you got an incorrect input (optionaly) give a message and loop asking

Possible code:

int number;
for (;;) {     // C idiomatic infinite loop
    printf("Please pick a number from 1 to 10 : ");
    if (scanf("%d", &number) != 1) {
        // non numeric input: clear up to end of line
        int c;    // c must be int to compare to EOF...
        while ((c = fgetc(stdin)) != EOF && (c != '\n'));
    }
    else if (number > 0 && number <= 10) break;   // correct input: exit loop
    // error message
    printf("last input was incorrect\n");
}
printf("Oh ! You have chosen %d\n", number);

If you want a more user friendly way, you could use different messages for non numeric input and incorrect values, but it is left as an exercise for you... (I am afraid I am too lazy ;-) )

Serge Ballesta
  • 143,923
  • 11
  • 122
  • 252
1

What you likely envision is a fine-grained control over the character-by-character input of the user; for example, anything but digits should be impossible; or when they type a 2 and try to type another digit, that should be impossible, too.

That's something we know from graphic user interfaces. It requires that your program is "informed" about every key stroke at once.

For historical reasons, this capability is not part of the C standard library. The reason is that historically all kinds of input devices were used, for example punch cards or paper-based teletypes. The communication was line by line: Input was local until the user hit the aptly named "enter" key. Any stupid device can do that, a lowest common denominator which is why all languages which do not define GUI elements adhere to it.

Obviously, character-by-character input is entirely possible on modern terminals and computers; but it is system specific and has never been standardized in the language. It is also likely more complicated than meets the eye if you want to give the user the opportunity to edit their input, a phase during which it may be "illegal". In the end you'll need to catch the point when they submit the entire value and validate it, which is something you can do even with the crude facilities that C provides.

Hints for an implementation:

  • Let the user complete a line of input. Validate it, and if the validation fails, prompt for another attempt. Do that in a loop until the input is valid.
  • Use scanf because it is convenient and error free (compared to home-grown input parsing).
  • This is something often overlooked by beginners: Check the return value of scanf which will indicate whether the input could be parsed (read the scanf manual!).
Peter - Reinstate Monica
  • 15,048
  • 4
  • 37
  • 62
0
int main()
{
    int number = 0;
    while (number < 1 || number > 10)
    {
        printf("please enter number between 1 - 10\n");
        scanf("%d", &number);
        if (number < 1 || number > 10)
        {
            printf("you entered invalid number!\n");
        }
    }
    return 0;
}
roee attias
  • 95
  • 1
  • 6
  • It would be best to check the return value from `scanf()`, breaking the loop if you get an error or EOF. You also need to worry about getting a return value of zero, which indicates that's what's in the input buffer is non-numeric. That will cause an infinite loop. – Jonathan Leffler Jul 20 '21 at 15:57
-1
while(1)
{
    //input ....
    if(number<0 || number>10)
    {
        // print error
        continue;
    } else {
        while (getchar() != '\n') ;
        break;
    }
}

I think I made a mistake at the beginning.A character can be checked by if but scanf can't. If scanf can't get the input in the specified format, the illegal input in the input buffer will be kept all the time.

After looking at another question, I thought that when the input is wrong, we should use getchar() to clear the buffer before the next input.

Yatogami
  • 69
  • 7