I'm creating a command line application with a prompt. It works fine as long as the input fits inside the buffer, but when the input is larger I get some weird behavior. Below is a simplified minimal example which has the same bug.
int main()
{
for (;;) {
const int size = 8;
char str[size];
printf("> ");
fgets(str, size, stdin);
toupper_str(str);
printf("Result: %s\n", str);
}
}
It works fine if the input is in smaller than size
.
> asdf
Result: ASDF
>
When the input is larger, the portion of the input in range is processed, and in the next loop iteration, the rest of the given input is immediately returned from fgets
. This leads to that portion of the input also being processed and some weird output.
> asdfghjk
Result: ASDFGHJ
> Result: K
>
I can see if the input is larger than or equal to size by comparing the last character to a newline. fgets
retains the newline as long as it fits.
fgets(str, size, stdin);
if (str[strlen(str) - 1] != '\n') {
fprintf(stderr, "Input too long\n");
}
When this is detected, how do I stop it from reading the rest of the too long input on the next iteration?
I've seen similar questions on here, but none that ask the same question.