K& R 1.6阵列示例不打印

时间:2012-07-05 22:36:55

标签: c

我最近买了C编程语言,并且慢慢地查看文本,确保我理解所有内容。我遇到了这个数组示例(第1.6章),由于Stack Overflow已经回答了许多问题,我完全理解了这一点。

问题是当我运行程序时,没有打印出来。这本书的习惯有时会让人感到愚蠢,所以如果这是一个noobie问题,我会提前道歉。我向你保证,我已经找了一段时间的答案。

这是文本中的代码。我正在使用XCode 4:

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

为什么不运行?

2 个答案:

答案 0 :(得分:3)

这一行:

    while ((c = getchar()) != EOF)

确保while循环继续,直到getchar()读取导致条件为假所需的字符。因此,在您输入EOF字符之前,它将继续 - 为了执行此操作,您需要使用组合键 Ctrl + D

答案 1 :(得分:3)

我没有发现您的版本与图书版本之间存在任何差异 - 我认为问题可能在于您正在运行该计划。

getchar()标准输入中读取字符。这可以是终端设备,到另一个程序的管道,甚至是网络套接字(很少见)。

当你运行这个程序时,它可能只是坐在那里直到你输入一些字符然后终止输入 - 如果你在一个新行上键入一个Control + D字符,大多数终端都会这样做

更容易通过易于重现的机制为程序提供一些输入 - 通过echo管道输入文件或内容:

./a.out < /etc/passwd
echo "hello world" | ./a.out

您可以使用任何程序代替echo - 您也可以使用ls(1)

ls | ./a.out
可悲的是,K&amp; R书籍在很多方面都很出色,但它大多忽略了开发和执行环境--C适用于规范不包含分层目录结构的大量机器,以选择一个简单的例子。