Create a user-defined function that should take one string parameter and it should return an integer value: the count or number of words in that string. Then, call it in the main ( ), where you should ask the user to enter any string value (can be an entire line), pass that value to the function being called, and display the returned value.
#include <iostream>
#include <string>
using namespace std;
int WordsCount(string str)
{
int count = 1;
for (int i = 0; i < str.length(); i++)
{
if (str.at(i) == ' ')
{
count++;
}
}
return count;
}
int main()
{
string str;
getline(cin, str);
cout << WordsCount(str);
return 0;
}
cpp programming exercise with solution