cgetchar

Why are two getchar() functions used?


I'm trying to write a program which task is to get rid of extra whitespace in a text stream.

#include <stdio.h>

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

I know that getchar() function returns a new character each iteration and we store the character in the c variable, but I can't figure out why do we need to assign c variable to getchar() in the second while loop again.


Solution

  • The inner loop loops as long as it extracts spaces from the stream, effectively skipping them. The result is that, if you have a sequence of spaces, the first one will be printed, and the rest will be discarded.

    You need to assign to c even there (as opposed to just doing something like while (getchar() == ' ');) because you'll reach a point where you extract a character that is not a space, so you need to remember what character it was to output it after the loop.