C++ How To Count Words in a String
Count Words in a String
Use a stringstream to read the words of a string one by one, and count them:
Example
string text = "I love learning C++";
stringstream ss(text);
string word;
int count = 0;
while (ss >> word) {
count++;
}
cout << "Number of words: " << count;
Explanation:
A stringstream (from the <sstream> library) lets you read from a string, just like cin reads from the keyboard.ss >> word reads one word at a time and skips the spaces. The loop stops when there are no more words.