yroc yroc - 2 months ago 7
C Question

C word count program fails when testing for whitespace

I created a simple word counting program ("word": sequence of characters that does not contain whitespace character). My idea is to count a word whenever the program gets a character

ch
such that
ch
is not a whitespace character, but the character preceding
ch
, call it
pre_ch
is a whitespace character.

The following program doesn't quite work (
nw
remains stuck at
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);
}


But, if I change the
if
clause to:

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


(remove the tab and newline options for
pre_ch
), the program works. I have no idea why.

Answer

While it looks natural, the compiler does not understand your intent when you write:

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

Instead you need to write:

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

That said, you might want to have a peek at isspace()in ctype.h