2014-08-31 61 views
0

我试图理解此代码,我很困惑: 我不明白为什么需要三次getchar函数,我无法理解何时程序是使用getchar函数。 的代码工作得很好,它从这里拿了: http://www.zetadev.com/svn/public/k&r/exercise.1-13.c试图理解此代码和getchar函数

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

回答

0

功能getchar()读取并返回从标准输入设备的字符。

语法是variable name = getchar(),变量可以是类型intchar

以下是每个getchar()调用的说明。

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

    这将检查,如果你输入EOF(即按Ctrl + d在UNIX和Ctrl + Z在Windows系统)

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

    这将检查你输入空格,制表符和换行符,如果是则跳过那些并返回while((c = getchar()) != EOF)

  3. length = 1;

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

    ++length;

    比空格,制表符和新行字符其他任何其它字符将导致执行++length

1

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))