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++
}
The negation of a || b
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')
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.