Search code examples
while-loopeofgetcharkernighan-and-ritchie

K&R 1-9 // using getchar in a loop inside a loop


I have this simple program:

main()
{
    int c;
    while ((c = getchar()) != EOF)
    {
        if (c == ' ')
        {
            while ((c = getchar()) == ' ');
            putchar(' ');

            if (c == EOF) break;
        }

        putchar(c);
    }
}

As I understand it, there are two loops. The condition for the first loop is for the output of getchar to be different then EOF (so implicitly the loop breaks at EOF); the condition for the second loop is that the output of getchar is not blank, then it'll output exactly one blank and if by any chance the non-blank character was EOF the whole program will interrupt.

Is it necessary to place a second check for EOF? Wouldn't it be "spotted" by the condition of the first loop?

How comes that the blank characters will be "consumed" by the second loop, but the first non-blank character is still there for the first getchar to be read?


Solution

  • Okay,

    The inner

    if (c == EOF) break;
    

    avoids the subsequent

    putchar(c);
    

    which would otherwise be performed if that cycle of the loop was completed.


    e.g.

    main()
    {
        int c;
        while ((c = getchar()) != EOF)
        {
            if (c == ' ')
            {
                while ((c = getchar()) == ' ');
                putchar(' ');
                if (c == EOF) break; // <<- This ...
            }
    
            putchar(c);             // <<- ... jumps past this.
        }
    }