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.
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++;
}
#include <iostream>
#include <string>
#include <sstream>
usingnamespace 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
#include <iostream>
#include <string>
usingnamespace 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.