I have a problem where if a user enters an input greater than the max number of characters such as "abcdefg" when the max is 5, the fgets()
that is within a loop runs twice and instead of "abcd" it instead prints out "abcd" then "efg".
I think this is because fgets()
only processes up to the 4 characters and a null terminator but there is still "efg" that exists in the stdin buffer.
I was wondering if there was a way to only grab the "abcd" and discard the rest of any remaining input that is more than the max size of the allocated buffer.
#define INPUT_MAX 5
int main(int argc, char* argv[]){
char input[INPUT_MAX];
while(1){
printf("prompt> ");
fgets(input, INPUT_MAX, stdin);
printf("\n%s\n", input);
}
}
Example RUN:
prompt> abcdefg <-- I press enter once here for /n
abcd
prompt>
efg
prompt> . <-- I end up here after enter command
I found that fflush(stdin)
is not a proper way to flush a stdin.