C ++ tutorial aims to count the number of words in a C language sentence under Code Blocks software.
To write this program we will need a single function with 4 variables: i a counter that will count the number of words, ph an integer to know if we have entered the sentence or not and n to count word by word and a character c to detect the point “.”
First we need a loop “while” to take into account that the sentence will be at least one word, after we will have a condition on the space that will be between the words so that it does not count as being a word.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | #include <iostream> using namespace std; int main() { char str[80]; cout << "Enter a string: "; cin.getline(str,80); int words = 0; // Holds number of words for(int i = 0; str[i] != '\0'; i++) { if (str[i] == ' ') //Checking for spaces { words++; } } cout << "The number of words = " << words+1 << endl; return 0; } |
Simple program to be able to count all the words in a text for example, that will avoid the risk of being mistaken and forget some if they are counted manually.