i have an issue with my code.
int startProg()
{
char *method;
method= malloc(30*sizeof(char));
int isInteger=0;
int num;
do{
printf("Seleziona il metodo \n");
fgets(method,30,stdin);
//it must be nothing more than 1 char inside
if (method[1]!= 10)
{
printf("Insert just one char \n");
}else{
if (method[0]>='1'&&method[0]<='4'){
switch (method[0]){
case '1':
num=1;
break;
case '2':
num=2;
break;
case '3':
num=3;
break;
case '4':
num=4;
break;
}
isInteger=1;
//check the option choose
}else{
printf("Inserire un carattere valido\n");
}
}
}while(isInteger==0);
free (method);
return num;
}
//terminal output
Seleziona il metodo
123456789123456789123456781345646
Inserire solo un carattere
Seleziona il metodo
Inserire solo un carattere
Seleziona il metodo
The idea is to recive a user input, check if is a number between 1 and 4, check witch value is and then return the value. The only issue is that when i insert a value with more than 30 digit. I have to clean the buffer and i need my code to be portable. Anyone as an idea? thanks
I think you want to clear all characters till the end of line if input was larger than the buffer reserved for
fgets()So, detect if that was the case
and you can implement
clearEOL()as one of these examples:Some people may prefer a for loop :-)
or even an infinite loop with
breakinside