Limit fgets input to up to a certain number of characters 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 &lt;stdio.h&gt;
#include &lt;stdlib.h&gt;
#include &lt;string.h&gt;

int main()
{
    char v[12];
    
    printf(&quot;Type a word with up to 10 chracters:\n&quot;);
    //Loop checks if fgets succeeded and if there is '\n' in the string:
    while (!fgets(v, 12, stdin) || strcspn(v, &quot;\n&quot;) == 11){
        if(feof(stdin)) {
             printf(&quot;Error: End of file reached.\n&quot;);
             exit(EXIT_FAILURE);
        }
        printf(&quot;Error: The word is longer than 10 characters, try again.\n&quot;);
        for(int ch=getchar(); ch != '\n' &amp;&amp; ch != EOF; ch=getchar());
        printf(&quot;Type a word with up to 10 chracters:\n&quot;);
    }
    v[strcspn(v, &quot;\n&quot;)] = '\0';
    
    printf(&quot;%s\n&quot;, 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?
This would obviously be better as a function, so we can call with different parameters.
Instead of repeating the constant 12 in the fgets() call, we could simply use sizeof v.  Then it remains consistent if we change v.
Instead of strcspn() with only one character, I'd prefer strchr().  Conveniently, that returns a null pointer if not found, so we don't need to calculate the length to search.  And we shouldn't repeat the search to replace the newline with null character.
Error messages should go to stderr, not stdout.
We can skip the rest of line with a simple scanf(&quot;%*[^\n]&quot;) (note the * to suppress assignment).  That would replace the ch loop.