Don't understand how the code is working.

Input and Output

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?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
#include <string>

using namespace std;

int main()
{
    string s;
    int c=0;

    getline(cin,s);

    for(int i=0; i<s.length(); i++)
    {
        if(s[i]>='A' && s[i]<='Z' || s[i]>='a' && s[i]<='z')
            c++;
        for(;(s[i]>='A' && s[i]<='Z')||(s[i]>='a' && s[i]<='z') && i<s.length();i++){}
    }

    cout<<c<<endl;

    return 0;
}
The code is equivalent to this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>
#include <string>
#include <ctype>

using namespace 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.
You may be getting tripped up by the fact that i is incremented in two places. For what it's worth, this is pretty ugly code to me.
But how it is detecting the spaces and counting the words?
its not clear to me.
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.
Topic archived. No new replies allowed.