word count

how do i make it so this program will count the words no matter how many spaces?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
/*****************************************************\
 * purpose - counts how many words are in a string                        *
\*****************************************************/


#include <iostream>
#include <string>
using namespace std;

int WordCount(string sentence);
int main()
{
    
    string Mystring;
    
    cout << " Type in the string you would like to use: " << endl;
    
    getline(cin, Mystring);          // inputs sentence
    
    cout << " Your string is: " << Mystring << endl;
    
    
    
    cout << " The string has " << WordCount(Mystring) << " words " << endl;
    
    
    system("pause");
    return 0;
}


// counts the words
int WordCount(string Sentence)
{
    int length = Sentence.length();        // gets lenght of sentence and assines it to int length
   
    int words = 1;                          
  
    
    for (int size = 0; length > size; size++)
    {
                 
        if (Sentence[size] == ' '/*space*/)
        words++;                   // ADDS TO words if there is a space
    }
    if ( Sentence[0] == ' '/*space*/ )
      words--; 
    return words;
}
Last edited on
Try changing at line #43 to:

1
2
if (Sentence[size] == ' ' && Sentence[size-1] != ' ') 
words++;


~psault
Last edited on
Topic archived. No new replies allowed.