gpt4 book ai didi

c - 试图理解这段代码和 getchar 函数

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:26:07 24 4
gpt4 key购买 nike

我试图理解这段代码,但我很困惑:我不明白为什么需要三次 getchar 函数,我不明白程序何时使用 getchar 函数。该代码运行良好,它取自这里: http://www.zetadev.com/svn/public/k&r/exercise.1-13.c

#include <stdio.h>

/* Exercise 1-13: Write a program to print a histogram of the lengths of words
in its input. It is easy to draw the histogram with the bars horizontal; a
vertical orientation is more challenging. */

/* At this point we haven't learned how to dynamically resize an array, and we
haven't learned how to buffer input, so that we could loop through it twice.
Therefore, I'm going to make an assumption that no word in the input will be
longer than 45 characters (per Wikipedia). */


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

main()
{
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');
}
}
}

最佳答案

这个getchar()是用来确保当到达EOF时,程序退出 while 循环。

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

这个getchar也是一个while循环。它确保跳过空白字符 ' ''\t''\n'

        while ((c = getchar()) && c == ' ' || c == '\t' || c == '\n')
;

为了使程序更健壮,上面这行实际上应该是:

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

这个getchar也是一个while循环。它认为任何不是 ' ''\t''\n' 的字符都是单词字符并增加长度对于每个这样的字符。

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

再一次,为了让程序更健壮,上面这行真的应该是:

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

关于c - 试图理解这段代码和 getchar 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25595100/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com