You need to check the returning value of your scanf:
#include <stdio.h>
void openMenu(int *op) {//edited
do {
printf("Your turn...
");
if (scanf(" %d", op) != 1 || *op > 14 || *op < 1 ) {
while(getchar()!='
'); // clean the input buffer
printf("Only enter a number between 1 and 14!
");
}
} while (*op > 14 || *op < 1 );
}
int main()
{
int op;
openMenu(&op);
printf("Number Read {%d}
", op);
return 0;
}
A more robust (and complicated) solution would be the following:
int isNumber(char buffer[]){
for(int i = 0; buffer[i] != ''; i++)
if(!isdigit((unsigned char) buffer[i]))
return 0;
return 1;
}
int readInput(char buffer[]){
int result = scanf("%99s", buffer);
while(getchar()!='
');
return result;
}
int isInRange(int *op, char buffer[]){
*op = atoi(buffer);
return *op <= 14 && *op >= 1;
}
void openMenu(int *op) {
do {
char buffer[100];
if(readInput(buffer) && isNumber(buffer) && isInRange(op, buffer)) {
break;
}
printf("Only enter a number between 1 and 14!
");
} while (1);
}
This would avoid that input such as 4odgjlda
would be considered a valid number. Nevertheless, with the current approach inputs such as 4 odgjlda
would still be considered as a valid input, since scanf
would read the first word and not the entire line. For a more robust solution you should use fgets
instead. One can see an example of such solution on the answer provided by Andreas Wenzel.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…