I have a problem with my code:
When I write any input different from 1,2,3,4 the output is
Inserire il numero dei giocatori
inserire un numero valido
Inserire il numero dei giocatori
inserire un numero valido
Inserire il numero dei giocatori
How can I fix it?
#include <stdio.h>
#include <stdlib.h>
#include <memory.h>
#include <time.h>
int controll_num(){
int controll=0;
int players;
char c;
do{
printf("Inserire il numero dei giocatori \n");
c=getc(stdin);
switch (c){
case 49:
players=1;
controll=1;
break;
case 50:
players=2;
controll=1;
break;
case 51:
players = 3;
controll=1;
break;
case 52:
players = 4;
controll=1;
break;
default:
printf("inserire un numero valido\n");
}
}while(controll==0);
return players;
}
int main(){
controll_num();
return 0;
}
Instead of
getc
usescanf
as for examplePay attention to the leading space in the format string. It allows to skip white space characters as for example the new line character
'\n'
that is placed in the input buffer by pressing the Enter key.As for
getc
then it can read white space characters.Also instead of using magic numbers like
49
as case labelsuse characters like
This will make your code more readable.