user12162556
user12162556

Reputation:

How to limit an integer's input to 2-12 only?

I want to strictly limit a user's input on an integer in this program to 2-12 only. How do I do that?

#include <stdio.h>

int main(){
    int i;
    scanf("%d", &i);
    int diceThrown, diceResult;
    int sum = 0; 
    for(diceThrown = 1; diceThrown <= i; diceThrown++){
        scanf("%d", &diceResult);   //limit this input to 2-12 only, how?
        sum += diceResult;
    }
    if(sum >= 40){
        sum = sum % 40;
        if(sum == 12){
            printf ("28\n");
        } else if(sum == 35){
            printf ("7\n");
        } else{
            printf ("%d\n", sum);
        }
    } else if(sum < 40){
        if(sum == 12){
            printf ("28\n");
        } else if(sum == 35){
            printf ("7\n");
        } else{
            printf ("%d\n", sum);
        }
    }
    return 0;
}

Also just to clarify, that I'm still a beginner in programming (like only 2 months into C.SCi course), so if you could explain it to me like I'm not a expert that would be great.

Upvotes: 0

Views: 123

Answers (2)

Lukas-T
Lukas-T

Reputation: 11350

scanf has no functionality to do what you want. You can just use an if to validate input.

if(scanf("%d", &diceResult) != 1 || diceResult < 2 || diceResult > 12) {
//handle invalid input here
}

If the input is invalid it is up to you what you want to do. You could ignore the input and ask the user to enter a valid number, you can quit the whole program or just ignore the error, or something else entirely.

You can also check the input repeatedly with an while:

while(scanf("%d", &diceResult) != 1 || diceResult < 2 || diceResult > 12) {
//prompt user to enter valid input here
}

As mentioned by chux, part of handling invalid input would be to cosume the invalid input and check for EOF.


The scanf("%d", &diceResult) != 1 will assure, that scanf actually read exactly one number and no parsing errors occurred.

Upvotes: 1

Consider this:

#include <stdio.h>

int main(){
    int x;
    do
    {
        printf("give a number between [2-12]\n");
        scanf ("%d",&x);
    }
    while(x<2 || x>12);
    return 0;
}

You can use a do-while loop so that you only take the values that are between the 2-12 range. That way you can force the user to give an integer as an input that is in the range that you ask for, in that case from [2,12]. Otherwise the program will turn back and request a valid input again.

Upvotes: 0

Related Questions