Search code examples
cgetchar

getchar issue when check read char against Enter key


I have a simple c code as follow:

#define RECORDS_PER_PAGE 24

int main(void) {
    int i = 0, n;
    char pause_char;

    printf("Enter a number as the stop point: ");
    scanf("%d", &n);

    while (++i <= n) {
        printf("i is: %d\n", i);
        if (i % RECORDS_PER_PAGE == 0) {
            printf("Press Enter to continue...");
            while((pause_char = getchar()) != '\n');
        }
    }
    return 0;
}

The problem is when I enter 30 as the stop point, I got the following output:

i is: 1
i is: 2
i is: 3
...
i is: 24
Press Enter to continue...i is: 25
...
i is: 30

I expect that the program stop when the if condition satisfies. But it continue without paying attention to getchar. But the strange part is when I enter for example 60 as the stop point it will give the following output:

i is: 1
i is: 2
i is: 3
...
i is: 24
(1) Press Enter to continue...i is: 25
...
i is: 30
...
i is: 46
i is: 47
i is: 48
(2) Press Enter to continue...
i is: 49
...
i is: 59
i is: 60

It will stop at (2) but not (1). I now that maybe something in the buffer cause this problem, but I don't understand why. Is there any explanation for it?


Solution

  • The problem is that when you read input you end the input by pressing ENTER, thus giving you your number and \n, like 30\n.

    So your scanf reads out the number and leaves \n in the stdin buffer, then getchar() comes along and reads a byte, the \n.

    Simple but ugly solution, add another getchar() to read out the \n. (Nicer way is to handle it in your scanf read directly.)