C程序,终端无打印

时间:2015-02-06 17:28:26

标签: c loops output getchar

我有以下c程序,应打印输入中单词长度的垂直直方图。

#include <stdio.h>

#define MAX_WORD_LENGTH     35      /* maximum word length we will support */

int main(void)
{
int i, j;                     /* counters */
int c;                        /* current character in input */
int length;                   /* length of the current word */
int lengths[MAX_WORD_LENGTH]; /* one for each possible histogram bar */
int overlong_words;           /* number of words that were too long */

for (i = 0; i < MAX_WORD_LENGTH; ++i)
    lengths[i] = 0;
overlong_words = 0;

while((c = getchar()) != EOF)
    if (c == ' ' || c == '\t' || c == '\n')
        while ((c = getchar()) && c == ' ' || c == '\t' || c == '\n')
            ;
    else {
        length = 1;
        while ((c = getchar()) && c != ' ' && c != '\t' && c != '\n')
            ++length;
        if (length < MAX_WORD_LENGTH)
            ++lengths[length];
        else
            ++overlong_words;
    }

printf("Histogram by Word Lengths\n");
printf("=========================\n");
for (i = 0; i < MAX_WORD_LENGTH; ++i) {
    if (lengths[i] != 0) {
        printf("%2d ", i);
        for (j = 0; j < lengths[i]; ++j)
                putchar('#');
            putchar('\n');
        }
    }
}

我把它编译为a.out,在终端我做./a.out,我输入一个单词,没有任何反应。有帮助吗?我是C的新手,只是想学习。

2 个答案:

答案 0 :(得分:3)

getchar()返回EOF之前,您的程序不会打印任何内容。这意味着输入一个单词并点击返回将不会这样做。您需要在空行上按^D以告知终端仿真器关闭输入流。

这里的快速测试似乎表明你的程序有效。您可能需要查看大&& / ||逻辑中的操作顺序 - clang在&&内向||发出了一些警告。

答案 1 :(得分:0)

您的代码中存在逻辑问题。

假设输入为“a”。然后用这个:

while ((c = getchar()) && c != ' ' && c != '\t' && c != '\n')
        ++length;

程序将进入无限循环,因为您未能检查EOF,这是非零。

尝试这样的事情:

int in_word = 0;
do {
    c = getchar();

    if ((c == EOF) || isspace (c)) {
        if (in_word) {
            in_word = 0;
            if (length < MAX_WORD_LENGTH) {
                lengths[length]++;
            }
            else {
                overlong_words++;
            }
        }
    }
    else {
        if (!in_word) {
            in_word = 1;
            length = 1;
        }
        else {
            length++;
        }
    }
} while (c != EOF);

测试时可以这样做:

$ echo -n "Lorem ipsum dolor sit amet" | ./main

它将为程序提供终止所需的EOF,可重复,并且无需每次都输入一些单词。

相关问题