I'm trying to write to a program that takes in an integer from the terminal and safely checks if it actually is an int and if it is equal to or in between 0 and 5. The code should also have retry logic.
This is the code that I have written:
#include <stdio.h>
#include <stdlib.h>
int main(){
int input;
char i[3];
char *p;
while(fgets(i, (sizeof(i)),stdin)){
input=strtol(i,&p,10);
if(input<0 || input>5 || p==i || (*p)!='\n'){
printf("please enter a integer larger or equal to 0 or smaller or equal to 5\n");
}
else{
printf("%d",input);
break;
}
}
}
The problem I have encountered is that if I input more characters than fgets()
reads such as "aaaaa", I get the output:
please enter a integer larger or equal to 0 or smaller or equal to 5
please enter a integer larger or equal to 0 or smaller or equal to 5
please enter a integer larger or equal to 0 or smaller or equal to 5
I'm assuming the issue is that the characters that fgets
does not read get left in the buffer and get read on subsequent iterations which trigger the if statement and therefore the repeated output. I'm assuming the solution is the somehow clear the buffer but from what I've read fflush()
isn't allowed. Is there a simple way to clear the buffer? And how would you go about doing it, if that actually is the issue to the problem?