Search code examples
cwhile-loopcharwhitespacegetchar

I don't understand how how this code works


I'm doing Exercise 1-9 in the K&R Book, while trying to find solutions I came across this code:

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

Why does the first if statement work if even if I input a letter. From my understanding it will only execute if the character I input is a blank space? Btw the exercise is making a program replace multiple consecutive blank spaces to a single one.


Solution

  • I've formatted out and comented the code. Hope that'll help. The code actually covert all sequence of spaces within stdin into one space:

     "123    456 a  b c  " -> "123 456 a b c "
    

    Code:

    
    int main() {
        int c;
     
        /* we read stdin character after character */
        while ((c = getchar()) != EOF) {
            /* if we have read space */   
            if (c == ' ') {
                /* we skip ALL spaces */
                while ((c = getchar()) == ' ')
                    ; /* skipping ALL spaces: we do nothing */
    
                /* and then we print just ONE space instead of many skipped */
                putchar(' ');
    
                /* if we at the end of stdin, we have nothing more to print */
                if (c == EOF) 
                    break;
            }
    
            /* we print every non space character */
            putchar(c);
        }
    }