So in the following bit of code I'm reading an option from the user to then decide whether to perform a given action:
printf("Do you want to execute %s: ", exe);
char input = getchar();
if (input == 'y') {
return execute(exe);
} return 0;
The problem I'm having is that after the line char input = getchar()
a character (I'm assuming an enter key or newline) gets stuck in stdin
, and a future call to fgets()
(reading from stdin
) from my execute()
function therefore eats up this stuck character and doesn't prompt the user for the required input.
Now I can define the following function to 'eat' any stray characters for me if called before calling execute()
...
void iflush() {
int c;
while ((c = getchar()) != EOF && c != '\n') {
continue;
}
}
... and this solves the problem. But I'm left wondering why this is happening in the first place? Is there a more 'proper' way of getting a char
from stdin
without causing this stray character which then messes up my other methods? I'm very new to C and am keen to be sure I'm learning good habits.
It seems odd that I have to add a helper method, even if simple, to prevent errors in my program just from recording some user input. I've tried using fgetc()
also but same problem.