简体   繁体   中英

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.

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 )

Because the while (c == ' ') is reading until it finds a non-space. So, it stops when you reach the 'n', but you are not putting that character. After the putchar(' ') , add a putchar(c); to print the character after the string of blanks.

因为在内部,当您获得“ n”时,然后在外部,而while条件中,您正在获得另一个字符,即“ o”。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM