【问题标题】:C Program, Nothing printing in terminalC程序,终端没有打印
【发布时间】:2015-02-06 17:28:25
【问题描述】:

我有以下 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 的新手,只是想学习。

【问题讨论】:

  • 用缩进正确地格式化你的代码,并在你的大 if 和 while 上加上大括号。我根本无法遵循此代码。

标签: c loops output getchar


【解决方案1】:

getchar() 返回EOF 之前,您的程序不会打印任何内容。这意味着输入一个单词并按回车键不会这样做。您需要在空白行按^D 来告诉您的终端模拟器关闭输入流。

这里的快速测试似乎表明您的程序有效。您可能想检查您的大 &amp;&amp;/|| 逻辑中的操作顺序 - 在 || 中,clang 给了我一些关于 &amp;&amp; 的警告。

【讨论】:

  • Ctrl+Z 用于 windows 终端。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-11-02
  • 1970-01-01
  • 2011-06-10
  • 2020-12-17
  • 2020-07-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多