How to stop entering characters stuck in the buffer? WITH

So, in the following code fragment, I read the parameter from the user, then to decide whether to perform this action:

printf("Do you want to execute %s: ", exe);

char input = getchar();

if (input == 'y') {
    return execute(exe);
} return 0;

The problem is that after the line the char input = getchar()character (I accept the input key or a new line) gets stuck in stdin, and the future call fgets()(read from) from my function execute(), therefore eats this stuck character and does not ask the user for the required input.

Now I can define the following function to “eat” any stray characters for me, if called before the call execute()...

void iflush() {
    int c;

    while ((c = getchar()) != EOF && c != '\n') {
        continue;
    }
}

... . , ? "" char stdin, , ? C , .

, , , . fgetc(), ​​ .

+4
1

, ?

, , %c ( fgetc()), . , %d, , . , . %c . , "".

, (, , ..), scanf()? , fgets().

C , .

- scanf(). fgets(), , , sscanf(). , : , scanf? ?

, fgets(), , , , . , , , .

strcspn(), :

char line[256];
if (fgets(line, sizeof line, stdin) == NULL) {
    /* handle failure */
}
line[strcspn(line, "\n")] = 0; /* remove the newline char if present */

char, 3 . :

char line[256];
char ch;
if (fgets(line, sizeof line, stdin) == NULL) {
    /* handle failure */
}
if (sscanf(line, "%c", &ch) != 1) {
    /* handle failure */        
}
/* Now you can use 'ch' to check if it 'y' */
+3

Source: https://habr.com/ru/post/1660962/


All Articles