Search code examples
cgetcharputchar

K&R exercise 1-9. Putchar and getchar


I was doing the exercise 1-9( Write a program to copy its input to its output, replacing each string of one or more blanks by a single blank) of this book and it seems I'm not quite getting it. So far this is my code:

#include <stdio.h>

int main() {
    int c;

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

    return 0;
}

It's wrong since the sentence hey(blank)(blank)(blank)now comes as hey ow. Always the first letter after de last blank is erased. I think it is a pretty silly bug but I can't see how to fix it. I'll appreciate any piece of advice. PS: sorry for my English and if you don't understand something, please tell me.


Solution

  • In this if statement (I have formatted it that it could be readable)

    if (c == ' ')
    {
        while (c == ' ')
        {
            c = getchar();
        }
        putchar(' ');
    }
    

    you are skipping the non-blank character that just has been read because in the outer loop

    while ((c = getchar()) != EOF)
    

    you are reading the next character.

    The program can be written for example the following way

    #include <stdio.h>
    
    int main( void )
    {
        int blank = 0;
        int c;
    
        while ( ( c = getchar() ) != EOF )
        {
            if ( !blank || c != ' '  ) putchar( c );
            blank = c == ' ';
        }
    
        return 0;
    }
    

    Take into account that according to the C Standard main without parameters shall be declared like

    int main( void )