【发布时间】:2016-01-02 17:23:05
【问题描述】:
我一直在阅读 K&R 的第一章,但我遇到了第一个问题。
#include <stdio.h>
/* count digits, white space, others */
main(){
int c, i, nwhite, nother;
int ndigit[10];
nwhite = nother = 0;
for (i = 0; i < 10; ++i)
ndigit[i] = 0;
while ((c = getchar()) != EOF)
if(c >= '0' && c <= '9')
++ndigit[c-'0'];
else if(c == ' ' || c == '\n' || c == '\t')
++nwhite;
else
++nother;
printf("digits =");
for (i = 0; i < 10; ++i)
printf(" %d", ndigit[i]);
printf(", white space = %d, other = %d\n",
nwhite, nother);
}
我在终端中的输出为零。我已经尝试了许多不同的变体,但似乎无法将其输出和数字。
非常感谢任何帮助!
【问题讨论】:
-
第一个错误 K&R 太老了,不要为了学习而阅读。阅读它只是为了了解语言的历史。你有一个非常 K&Rish 的错误,
main()必须返回int。 -
做
./a.out < test.txt -
你能运行一个“hello world”程序吗?
-
你的程序适合我。从 shell 传递输入时,您是否按
Ctrl-C而不是Ctrl-D? -
它工作正常。输入内容并按
ctrl+D。(c = getchar()) != EOF的含义是它读取您键入的字符并等待直到您按下ctrl+D并打印字符统计信息。