Zoey Malkov
Zoey Malkov

Reputation: 832

How do I count the number of words if the user enters multiple lines/spaces?

I have a char array, which contains what the user has inputted. How would I count the words? The user in permitted to to do something crazy like:

hello this
               is a test
   how are
you today?

So the number of words here should be 9 but my program tells me 23. Why is this not working? Its counting the spaces, but I have taken that into account with sentence_entered[i + 1] != ' '

My code:

int i = 0;    
while (sentence_entered[i] != '\0') {

        if (
            (sentence_entered[i] == ' ' ||
            sentence_entered[i] == '\n') &&
            (sentence_entered[i + 1] != ' ' ||
            sentence_entered[i + 1] != '\n')
           ) {
            words += 1;
    }
i++
}

Upvotes: 0

Views: 47

Answers (1)

Pascal Cuoq
Pascal Cuoq

Reputation: 80255

The negation of a || b is !a && !b.

Your condition should read:

       (sentence_entered[i] == ' ' ||
        sentence_entered[i] == '\n') &&
        (sentence_entered[i + 1] != ' ' &&
        sentence_entered[i + 1] != '\n')

Upvotes: 5

Related Questions