I recently learned about the keyboard buffer and how important it is to clean it after getting input from the user. So I made this function to handle that:
// Get input from user
void get_input(char *buff, int size)
{
fgets(buff, size, stdin);
int newlineIndex = strcspn(buff, "\n");
/* If no newline is found, fgets stopped at `size` and
didn't read all input. Keyboard buffer is dirty */
if (newlineIndex == strlen(buff))
{
// Clear keyboard buffer
int c;
while ((c = getchar()) != '\n' && c != EOF);
}
else
{
// Remove newline from buff
buff[newlineIndex] = '\0';
}
}
Here, buff is where you want to store the input and size is sizeof(buff). After using fgets to read input from the user, I then look for the \n character left by fgets with strcspn(). If newlineIndex == strlen(buff), the \n newline wasn't found, which means that the user has typed more characters than size, so I proceed to clear the keyboard buffer with:
int c;
while ((c = getchar()) != '\n' && c != EOF);
else, the keyboard buffer didn't get dirty, so I remove \n from the user input to handle with it more easily as a string later.
Is my code okay or am I missing something? Is there a more efficient way to do it?