Prompt the user to enter a sentence read in AT MOST 80 chara
Solution
#include <iostream>
using namespace std;
void word_count(char str[]); // function prototype
int main()
{
char s[100]; // keeping the string length more than 80 for robustness
int len; // temporary variable to check the input string length
cout<<\"Enter any string of more than 80 characters:\";
cin.getline(s,81); // consider only first 80 characters (+1 for null character) from input string
for(len=0; s[len]!=\'\\0\';len++); // Loop through the string to make sure that only 80 characters are
// taken in consideration.
cout<<\"The length of the string is : \"<<len<<endl ; // should input <=80 (if input is less than 80 character, then
// all the characters are copied to s)
word_count(s); // call the word_count function to calculate the number of words in the 80 chars string
return 0;
}
void word_count(char str[])
{
int words=0;
for(int i=0;str[i]!=\'\\0\';i++)
{
if (str[i]==\' \' || str[i]==\' \') // check for spaces or Tabs
words++; // store the word count value
}
cout<<\"The number of words=\"<<words+1<<endl;
}
