Search code examples
cpasswordsexitfgets

C - Program exits when input exceeds fgets allowance


I have the following program written in C:

The main problem with this program is that if the input exceeds 80 characters when using fgets() function, the program just exits immediately. The other code is executed, however it does not wait for the user to press enter. It like simply ignores the getchar at the end.

How can I solve this problem please?


Solution

  • If the user input is longer than the 79 characters that fgets may read from stdin (it can read at most one less than its size parameter says, since it 0-terminates the buffer), the remaining input is left in the input buffer, hence the getchar() at the end immediately succeeds.

    To avoid that, you need to clear the input buffer if the input was too long.

    The problem is that if the input was short enough, you don't know whether to clear the buffer or not. So check whether you actually got a newline read in by fgets,

    int len = strlen(password);
    if (password[len-1] == '\n') {
        // got a newline, all input read, overwrite newline
        password[len-1] = 0;
    } else {
        // no newline, input too long, clear buffer
        int ch;
        while ((ch = getchar()) != EOF && ch != '\n');
        if (ch == EOF) {
            // input error, stdin closed or corrupted, what now?
        }
    }