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.