Search code examples
cgetchar

K&R Exercise 1-9 solution C programming


The task is to make a C program that replaces multiple blanks with a single blank and I found this solution on another StackOverflow question:

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

It works but I am puzzled by the second while loop:

while ((c = getchar()) == ' ')
            ;

How does line this even remove any white spaces? I thought it just does nothing until it comes across another non-blank character. So then if a sentence had 4 blanks then I would expect it to turn into 5 blanks because your just adding another blank with putchar(' ') ? Does it remove the excess blank spaces in a way I'm not aware of?


Solution

  • The program reads (using getchar) a string from standard input and the outputs (using putchar) the same string to standard output but leaving out the excess spaces. So effectively it "removes" the extra spaces.

    The while loop skips over a consecutive block of whitespace in the input while outputting nothing, and then after the loop is done, outputs a single space. That's how it "removes" the spaces.