Word Counting Project

something is wrong with the if statement, since the words int doesn't change at all

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

using namespace std;
int words=1;
int main()
{
    string phrase;
   cout <<"Word Counting Project: "<<endl;
   cout<< "Please enter in a phrase: "<<endl;
  cin>> phrase;
   for(int i=0; i< phrase.length(); i++){
    if(phrase.find(' ',i)==true){
            words++;
    }else{

    }
   }
   cout << "The Number Of Words: "<<words<<endl;
return 0;
}
.find() doesn't return true/false. It returns the index if found or string::npos if not found. See http://www.cplusplus.com/reference/string/string/find/

Also note that cin >> phrase will only obtain chars upto the first white-space char (space, tab, newline). You should use getline(cin, phrase) which allows a whole line to be entered.
Last edited on
Thank you for the getline(cin, phrase); thing, but how am I supposed to fix the .find() problem?
I have some code here from one of my projects you can modify for your use.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
string stringToSearch = "This is a string of text to search.";
	string stringToFind{};

	cout << stringToSearch << endl;

	cout << "Enter a string to find" << endl;

	getline(cin, stringToFind);

	int wordAppearance{};

	for (int position = stringToSearch.find(stringToFind, 0); position != string::npos; position = stringToSearch.find(stringToFind, position))
	{
		cout << "Found " << ++wordAppearance << " instances of " << stringToFind << " at position " << position << endl;
		position++;
	}
1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>
#include <string>
#include <sstream>
using namespace std;

int main()
{
   string phrase, item;
   int words = 0;
   cout<< "Please enter a phrase: ";   getline( cin, phrase );
   for ( stringstream ss( phrase ); ss >> item; ) words++;
   cout << "The number of words = " << words << '\n';
}


Please enter a phrase: There's a lady who's sure all that glitters is gold, and she's buying a stairway to heaven
The number of words = 17
Last edited on
Something like using .find():

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

int main()
{
	string phrase;

	cout << "Word Counting Project:\n";
	cout << "Please enter in a phrase: \n";
	getline(cin, phrase);

	size_t words {!phrase.empty()};

	for (size_t i = 0; i < phrase.length(); ++i)
		if ((i = phrase.find(' ', i)) != string::npos)
			++words;
		else
			i = phrase.length();

	cout << "The Number Of Words: " << words << '\n';
}


Note this doesn't take into account a phrase that ends with a space - nor for multiple spaces etc. In this case the count is not correct.
Last edited on
Topic archived. No new replies allowed.