计算空白,制表符和换行符的程序输出

时间:2014-12-18 21:24:11

标签: c

我的问题涉及以下程序:

#include<stdio.h>
// program counts blanks, tabs, and new lines
main()
{
    int c;
    int blank, tab, newl;

    while((c = getchar()) != EOF) {
        } if (c == '    ') {
            ++blank;
        } if (c == '\t') {
            ++tab;
        } if (c == '\n') {
            ++newl;
    }

    printf("There are %d blank lines, %d tabs, and %d new lines\n", blank, tab, newl);
}

当我按下CTRL + Z时,我的输出是:有8个空行,56个标签,2147344384个新行

1)为什么程序输出? 2)getchar()从哪里获取此输入? 3)当我在MinGw控制台中执行程序时,为什么当我按下ENTER时程序会不断移动到下一行?只有按下CTRL + Z后才能得到上面提到的输出。

感谢。

2 个答案:

答案 0 :(得分:4)

更小,更简单的版本:

int main()
{
    int c;
    int count[255] = {0};

    while((c = getchar()) != EOF)
    {
        count[c]++;
    }

    printf("There are %d blank lines, %d tabs, and %d new lines\n",
        count[' '],
        count['\t'],
        count['\n']);

    return 0;
}

答案 1 :(得分:3)

只需初始化变量

#include<stdio.h>
// program counts blanks, tabs, and new lines
int
main()
{
    int c;
    int blank, tab, newl;

    blank = tab = newl = 0;
    while((c = getchar()) != EOF) {
        // } if (c == '    ') { this is wong
        if (c == ' ') {
            ++blank;
        } else if (c == '\t') { // add else, you don't need to check this if the previous was true.
            ++tab;
        } else if (c == '\n') {
            ++newl;
        }
    }

    printf("There are %d blank lines, %d tabs, and %d new lines\n", blank, tab, newl);
    return 0;
}