mercredi 9 mai 2018

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++
}

Aucun commentaire:

Enregistrer un commentaire