2016-09-25 4 views
1

シンプルな単語カウントプログラム(「単語」:空白文字を含まない文字列)を作成しました。私の考えは、プログラムが文字chを取得するたびに単語を数えることです。chは空白文字ではありませんが、chより前の文字は、pre_chと呼ばれ、空白文字です。空白をテストするときにCの単語カウントプログラムが失敗する

/* 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句を変更した場合::

次のプログラムはかなりの仕事(nw0に残ったまま)しません

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

(タブと改行を削除しますpre_chのオプション)、プログラムが動作します。なぜ私は考えていない。

+4

これは数十の複製がありますが、見つけにくいです。 '||'はリストのようには動作しません。条件リストのセパレータのように動作します。 'ch!= '' && ch!= '\ t' && ch!= '\ n''と続きます。 – dasblinkenlight

+1

'if(!isspace(ch)&& isspace(pre_ch))' – BLUEPIXY

答えて

4

それは自然な見えますが、あなたが書くとき、コンパイラがあなたの意図を理解していない:

あなたが書く必要がある代わりに
if ((ch != (' ' || '\t' || '\n')) && 
     (pre_ch == (' ' || '\t' || '\n'))) 

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

あなたがのぞき見を持っている場合があります、と述べましたat isspace() in ctype.h

関連する問題