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
句を変更した場合::
次のプログラムはかなりの仕事(nw
が0
に残ったまま)しません
if ((ch != (' ' || '\t' || '\n')) &&
(pre_ch == (' ')
(タブと改行を削除しますpre_ch
のオプション)、プログラムが動作します。なぜ私は考えていない。
これは数十の複製がありますが、見つけにくいです。 '||'はリストのようには動作しません。条件リストのセパレータのように動作します。 'ch!= '' && ch!= '\ t' && ch!= '\ n''と続きます。 – dasblinkenlight
'if(!isspace(ch)&& isspace(pre_ch))' – BLUEPIXY