Advertisement
janac

Count words in text

Dec 3rd, 2021
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.82 KB | None | 0 0
  1.  
  2. #include <iostream>
  3. #include <string>
  4. using namespace std;
  5.  
  6. int main()
  7. {
  8.     string text; // The text to be counted.
  9.     int number_of_words = 0; // Total number of words.
  10.     int last_space = 0; // Last space in the text.
  11.  
  12.     cout << "Enter your text:\n";
  13.     getline(cin, text); // Get the text.
  14.     // Check the text.
  15.     for (int i = 0; i < text.size(); ++i)
  16.     {
  17.         if (text[i] == ' ') // If there is a space,
  18.         {
  19.             ++number_of_words; // Count it.
  20.             last_space = i; // Note where the last space is.
  21.         }
  22.     }
  23.  
  24.     // If there is a word after the last space,
  25.     if (last_space != (text.size() - 1))
  26.     {
  27.         number_of_words += 1; // Add one word.
  28.     }
  29.  
  30.     cout << "This text has " << number_of_words << " words.\n";
  31.  
  32.     // End the program.
  33.     return 0;
  34. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement