0

By taking an input from a user such that if the user inputs anything above the limit, the program would only use the input from the beginning to the limit.

However, using fgets once again will read from the same string, which can be undesired.

Because it's not recommended to use fflush on stdin, and some operating systems wouldn't behave similarly or allow it, is there any conventional way of clearing stdin buffer without terminating the program?

Here is a sample snippet:


#include <stdio.h>
#include <string.h>
int main(void)
{
    printf("Input anything less than 10 characters\n");
    char str[10];
    while (1)
        {
            //fgets the first 10 characters of the input and ignore anything after the first 10 characters
            char input[10];
            fgets(input, 10, stdin);
            //when the user inputs more than 10 characters, the program will ignore the rest of the input
            if (strlen(input) > 10)
                {
                    continue;
                }
            //print the input
            printf("%s\n", input);
            break;
        }
    fgets(str, 10, stdin);
    printf("%s\n", str);
    return 0;
}
Edit:

I looked over other answers surrounding this topic, while while ((c = getchar()) != '\n') ; might help solving this problem, I am hoping to a conventional way that doesn't necessarily rely on looping over.

  • 1
    It really depends on what you mean by "clearing the buffer", which is an ambiguous phrase. If you mean discard all data up to the next newline, then you just read all the data up to the next newline. – William Pursell Oct 07 '21 at 16:01
  • 1
    `if (strlen(input) > 10)` <<-- this condition will never evaluate to true.(Hint: read the manual page for fgets()) – wildplasser Oct 07 '21 at 16:04
  • 1
    It would be unwise to clear more than to the next newline. Consider what will happen if the input is redirected from a file. – Weather Vane Oct 07 '21 at 16:39

0 Answers0