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

我的问题涉及以下方案:

#include // 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后才能得到上面提到的输出。

谢谢。

更小,更简单的版本:

 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; } 

只需初始化变量

 #include // 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; }