请解释一下......我被困了

时间:2016-01-11 00:49:50

标签: c

我已经开始做c了,而且我已经开始做了dennis ritchie和brian kernighan的c编程书......我坚持练习1.9" 编写交流程序将其输入复制到其输出中,用一个空格替换一个或多个空格的每个字符串" ...我尝试了很多方法...查看互联网和找到答案但没有解释...... 我看过一个看起来像

的代码
#include <stdio.h>
main()
{
    int c, last;
    last = EOF;
    while ((c = getchar()) != EOF) 
    {
    if (c != ' ')
        putchar(c);
    if (c == ' ') 
        {
        if (last != ' ')
        putchar(c);
        }
    last = c;
    }
}

所以请有人解释一下或给我另一个代码并附上适当的解释

谢谢

1 个答案:

答案 0 :(得分:1)

#include <stdio.h>
main()
{
    int c, last;
    last = EOF;

    /* while we get a char that isn't EOF */
    while ((c = getchar()) != EOF) {
        /* if it's not a space, print it */
        if (c != ' ')
            putchar(c);
        /* otherwise, if the previous char was not a space, print it */
        if (c == ' ') 
            if (last != ' ')
                putchar(c);
        last = c;
    }
}

此代码可以更简单地编写为

#include <stdio.h>
main()
{
    int c, last;

    /* while we get a char that isn't EOF */
    for (last = EOF; (c = getchar()) != EOF; last = c) {
        /* if it's not a space, print it */
        if (c != ' ')
            putchar(c);
        /* otherwise, if the previous char was not a space, print it */
        else
            if (last != ' ')
                putchar(c);
    }
}