This question is an extension of this other question from Stackoverflow.
The objective is to limit the input of characters read by fgets to up to a certain number of characters. And in the following code, that I've come up with as a solution, we are working with a limit of 10 characters as an example:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char v[12];
printf("Type a word with up to 10 chracters:\n");
//Loop checks if fgets succeeded and if there is '\n' in the string:
while (!fgets(v, 12, stdin) || strcspn(v, "\n") == 11){
if(feof(stdin)) {
printf("Error: End of file reached.\n");
exit(EXIT_FAILURE);
}
printf("Error: The word is longer than 10 characters, try again.\n");
for(int ch=getchar(); ch != '\n' && ch != EOF; ch=getchar());
printf("Type a word with up to 10 chracters:\n");
}
v[strcspn(v, "\n")] = '\0';
printf("%s\n", v);
return 0;
}
It works as intended. However @chux-ReinstateMonica has pointed out that there may still be corner weaknesses and possible improvements to be made to this solution.
So, how can this code/solution be improved?