Search code examples
cbashinputgetchar

Simple char-counting program behaves strangely


This code is expected to count the characters user inputed, except '\n', expect '\n's following other '\n'. I'll explain this later.

#include <stdio.h>

int main () {
        int numberOfChars = 0;

        do {
                while(getchar() != '\n')
                        numberOfChars++;
        } while(getchar() != EOF && numberOfChars++);

        printf("Number of chars = %d\n", numberOfChars);

        return 0;
}

Here are some examples:


Input: A, B, C, Ctrl + D

Expected output: 3

Actual output: Program doesn't terminate, and on the screen displays 123^D.


Input: A, B, C, Enter, Ctrl + D

Expected output: 3

Actual output: 3


Input: A, B, C, Enter, A, B, C, Enter, Ctrl + D

Expected output: 6

Actual output: 6


Input: A, B, C, Enter, Enter, Ctrl + D

Expected output: 4

Actual output: Program doesn't terminate, and on the screen displays:

abc

^D

I'm using OS X-10.10.5, bash-3.2 and clang-700.1.81.

Thanks in advance.


Solution

  • When the inner loop gets EOF returned, that is not equal to '\n', so the loop tries again, gets another EOF, and it still isn't a '\n', so it has another go. Computers are very patient…

    In the inner loop, use:

    int c;
    while ((c = getchar()) != EOF && c != '\n')
        numberOfChars++;
    

    This will stop on EOF or when the end of line is reached.

    See also my discussion attached to your answer — though I missed the EOF problem for the inner loop.