C单词计数程序在测试空格时失败



我创建了一个简单的单词计数程序("word":不包含空白字符的字符序列)。我的想法是,每当程序获得字符ch时,计数一个单词,这样ch不是空白字符,但ch之前的字符称为pre_ch是空白字符。

下面的程序不太工作(nw仍然卡在0):

/* Program to count the number of words in a text stream */
#include <stdio.h>
main()
{
  int ch;                       /* The current character */
  int pre_ch = ' ';             /* The previous character */
  int nw = 0;                   /* Number of words */
  printf("Enter some text.n");
  printf("Press ctrl-D when done > ");
  while ((ch = getchar()) != EOF)
  {
    if ((ch != (' ' || 't' || 'n')) && 
        (pre_ch == (' ' || 't' || 'n')))
    {
      ++nw;
    }
    pre_ch = ch;
  }
  printf("nThere are %d words in the text stream.n", nw);
}

但是,如果我将if子句更改为:

if ((ch != (' ' || 't' || 'n')) && 
    (pre_ch == (' ')

(删除pre_ch的制表符和换行符选项),程序工作。我不知道为什么。

虽然看起来很自然,但当你写

时,编译器并不理解你的意图:
   if ((ch != (' ' || 't' || 'n')) && 
        (pre_ch == (' ' || 't' || 'n')))

你应该这样写:

if ((ch != ' ' || ch != 't'|| ch != 'n') &&
(pre_ch == ' ' || pre_ch == 't' || pre_ch == ’n'))

也就是说,您可能想在ctype.h

中查看isspace()

最新更新