这是丹尼斯和S关于C语言的一本书的任务
练习1-13.编写一个程序来打印长度的直方图 它的输入中的单词.
这是我的代码(S没有完成,但我无法继续,因为我不知道发生了什么.):
#include<stdio.h>
#define MAXLENGTH 50
int main() {
int c, wlength;
int wlengths[MAXLENGTH];
/* init array with 0s */
for (int i = 0; i < MAXLENGTH; ++i)
wlengths[i] = 0;
wlength = 0;
while((c = getchar()) != EOF) {
if(c == ' ' || c == '\t' || c == '\n') {
/* Word is finished, increase count for the length */
++wlengths[wlength];
/* Reset the counter for the next word */
wlength = 0;
} else {
/* Word is still going */
++wlength;
}
}
printf("RESULTS:\n");
for(int i = 0; i < MAXLENGTH; ++i) {
printf("%d\n", wlengths[i]);
}
return 0;
}
编译启动程序(我也试用了GCC)
C:\Users\den\Documents\workspace\cexercixe> clang histogram.c
C:\Users\den\Documents\workspace\cexercixe> ./a.exe
然后我开始键入以下内容(用于测试):
a as asd asdf
123 123
输出:
RESULTS:
0
这对我来说毫无意义.谁能告诉我我做错了什么?我也试着添加了fflush(stdout)
,这并没有改变任何事情.
谢谢