Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <string>
- using namespace std;
- int main()
- {
- string text; // The text to be counted.
- int number_of_words = 0; // Total number of words.
- int last_space = 0; // Last space in the text.
- cout << "Enter your text:\n";
- getline(cin, text); // Get the text.
- // Check the text.
- for (int i = 0; i < text.size(); ++i)
- {
- if (text[i] == ' ') // If there is a space,
- {
- ++number_of_words; // Count it.
- last_space = i; // Note where the last space is.
- }
- }
- // If there is a word after the last space,
- if (last_space != (text.size() - 1))
- {
- number_of_words += 1; // Add one word.
- }
- cout << "This text has " << number_of_words << " words.\n";
- // End the program.
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement