基本C程序中没有输出

时间:2016-01-02 17:23:06

标签: c output

我一直在阅读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);

}

我在终端输出零。我尝试了很多不同的变体,但似乎无法将其输出和数字。

非常感谢任何帮助!

3 个答案:

答案 0 :(得分:2)

此程序需要传递一个输入文件,但它按原样运行。

 gcc test.c -o test
 echo "12345" > data
 ./test < data

 digits = 0 1 1 1 1 1 0 0 0 0, white space = 1, other = 0

这是另一个输出:

 echo "111 111 222" > data
 ./test < data

 digits = 0 6 3 0 0 0 0 0 0 0, white space = 3, other = 0

答案 1 :(得分:0)

问题是,您通常不会从控制台输入EOF。如Tony Ruths answer中所述,它通过将文件重定向到程序的stdin来工作,因为文件由EOF终止。由于整个文件随后被传递到stdin,程序通过getch()读取,“输入结束”被正确识别。

您只是无法通过控制台输入EOF,因此无法获得任何输出。 (实际上EOF

可能有一些特殊的快捷方式

答案 2 :(得分:0)

顺便说一下,自K&amp; R问世以来,我们已经学到了很多关于什么使代码更可靠/可维护的知识。一些例子:

#include <stdio.h>

/* count digits, white space, others */

int main ( void ) {                 /* type explicitly */

        int c;                      /* declare 1 variable per line */
        int i;
        int nwhite     = 0;         /* initialize variables when possible */
        int nother     = 0;
        int ndigit[10] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0};

        while ((c = getchar()) != EOF) {          /* use brackets */
                if ((c >= '0') && (c <= '9')) {   /* explicit precedence is clearer */
                        ++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]); /* 1 liner is ok w/{} */
        printf(", white space = %d, other = %d\n", nwhite, nother);
        return 0;                            /* don't forget a return value */
}