Search code examples
cfgets

Issues regarding taking input in fgets()


In this program the fgets() function is taking the previous enter as an input which is '\n' and hence not taking any input from the user. How to solve this issue ?

#include <stdio.h>

int main() {
    int n;
    scanf("%d", &n);
    char word[n + 1];
    fgets(word, n + 1, stdin);
    puts(word);
    
    return 0;
}

Solution

  • scanf("%d", &n) indeed stops at the first character after the number, if any. So the remaining characters typed by the user upto and including the newline are left pending in stdin.

    You can flush this ending input with a loop.

    Here is a modified version:

    #include <stdio.h>
    
    int flush_input(FILE *fp) {
        int c;
        while ((c = getc(fp)) != EOF && c != '\n')
            continue;
        return c;
    }
    
    int main() {
        int n;
        if (scanf("%d", &n) == 1) {
            flush_input(stdin);
            char word[n + 1];
            if (fgets(word, n + 1, stdin)) {
                puts(word);  // will output an extra newline
            }
        }
        return 0;
    }