Write a C++ program that will read a line of text and count the number of words in a text.
Write a C++ program that will read a line of text and count the number of words in a text.
Answer: read the whole line with getline, then count each place where a word starts (a non-space character after a space or at the beginning).
#include <iostream>
#include <string>
using namespace std;
int main() {
string line;
int words = 0;
bool inWord = false;
cout << "Enter a line of text: ";
getline(cin, line);
for (char ch : line) {
if (ch == ' ' || ch == '\t') {
inWord = false;
} else if (!inWord) {
inWord = true; // a new word starts here
words++;
}
}
cout << "Number of words = " << words << endl;
return 0;
}
Explanation: getline reads spaces too (cin >> would stop at the first space). The flag inWord tracks whether we are inside a word. Each time a non-space character appears while inWord is false, a new word has begun, so the count increases. This handles extra spaces between words and at the start or end correctly, unlike simply counting spaces + 1.
Sample: " C++ is fun " gives Number of words = 3.
Log in or create a free account to answer this question.