2

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.

Richard Chambers
  • 16,643
  • 4
  • 81
  • 106
Jae Yang
  • 479
  • 3
  • 13
  • 1
    `for (int c; (c = getchar()) != EOF && c != '\n';);` ? – KamilCuk Mar 21 '19 at 14:21
  • 2
    Possible duplicate of [How to clear stdin before getting new input?](https://stackoverflow.com/questions/36715002/how-to-clear-stdin-before-getting-new-input) – Raymond Chen Mar 21 '19 at 14:21

1 Answers1

4

There's nothing automatic. Check whether the input ends with newline. If it doesn't, call getchar() in a loop until you get newline or EOF.

while(1){
    printf("prompt> ");
    if (fgets(input, INPUT_MAX, stdin) == NULL) {
        break;
    }
    printf("\n%s\n", input);
    if (input[strlen(input)-1] != '\n') {
        for (int c; (c = getchar()) != EOF && c != '\n';)
            ;
}
Barmar
  • 741,623
  • 53
  • 500
  • 612