Input to your program will consist of a series of lines, each line containing multiple words (at least one). A ``word'' is defined as a consecutive sequence of letters (upper and/or lower case).
Your program should output a word count for each line of input. Each word count should be printed on a separate line.
Sample Input
Meep Meep!
I tot I taw a putty tat.
Sample Output
2
7
The solution is given here...I can't understand how the code is working? How it is ignoring the dots, detecting the words and counting?
#include <iostream>
#include <string>
#include <ctype>
usingnamespace std;
int main()
{
string s;
int c = 0;
getline(cin,s);
for(int i=0; i<s.length(); i++)
{
if(isalpha(s[i])
c++;
for(; i < s.length() && isalpha(s[i]); i++);
}
cout<<c<<endl;
return 0;
}
As you can see, the code only checks for letters of the English alphabet in the inner loop and exits the inner loop once it finds something that is not a letter.
When it sees a letter at line 15 it is at the beginning of a word and it increments c (the count of words). Line 17 then skips subsequent letters until it hits a non-letter. That where it detects spaces, along with anything else that isn't a letter.