How to prompt the user to enter a integer within a certain amount of numbers

时光怂恿深爱的人放手 提交于 2019-12-13 11:28:45

问题


I was trying to figure out what statement to use to get the user to enter a number between 1 and 10.

here is what i have so far.

int a;
printf("Enter a number between 1 and 10: \n);
scanf("%d", &a);

回答1:


int input;

while (true){
    scanf("%d",&input);
    if (input>=1 && input<=10){
        // process with your input then use break to end the while loop
    }
    else{
        printf("Wrong input! try Again.");
        continue;
    }
}



回答2:


Number beteween 1 to 10 right? so first stage you must validate if input is integer or not then you will check for range,

Below code is what i mention

#define MAX_RANGE 10
int input;
if (scanf("%d",&input) != 1) 
{
    printf ("Really bad input please enter integer number like in range 1 - 10\n");

}

Now in second stage as follows

if (input < 1 || input > MAX_RANGE) {
   printf("It's an integer but out of range error\n");
}

You can also use while..loop for same as follows

int input;

while (scanf("%d", &input) == 1 && input > 1 && input < 10)

{

    // process your input

}



回答3:


Why not use the do .. while loop?

int a;

do {
  printf("Enter a number between 1 and 10: \n");
  scanf("%d", &a);
} while (a < 1 || a > 10);


来源:https://stackoverflow.com/questions/21770397/how-to-prompt-the-user-to-enter-a-integer-within-a-certain-amount-of-numbers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!