Word count assuming well formed sentence – CSKC
Sign In

Search

Solved Problem #CPP#2632    siteicon   siteicon  

Problem Statement - Word count assuming well formed sentence

Write a program to count words in a given input sentence by a user, assuming that the sentence is well formed in a way that there are no initial or leading spaces and no extra spaces between words.

Solution

TC++ #2632

 

×

Ask AI About This Code

Default Prompt that is passed along with the code is given below, You can write your own prompt if you so desire.



×

Test CPP

  Related ( ? ) :

char str[101]; cout<<“Input a sentence (Less than 100 chars): ” ; cin.getline(str,80);
Collecting user input string. char array size is 1 more as space for null termination is given if full 100 character sentence is given.

int wc=0; //Word count variable wc initialised to 0.
for(int i=0;str[i]!=”;++i) //Loop till end of sentence by checking up to null termination character
{
if(str[i]==’ ‘) wc++; //word count is increase as soon as space character is found in the string.
}

cout <<“No. of words in given sentences = “<<wc+1<<endl;
Since there would be no space after the last word so counted spaces are increased by 1 to account for last word. Remember that we are talking of well formed sentences.

 

Notes

  • This code is quite condition specific. If enter is given directly without giving any word then it gives output as 1.
  • It also gives incorrect output for extra spaces any where in the sentences.
  • Independent punctuation can also be counted as words.


Share

Created: 14-Jan-2018 22:58 | Updated: 17-Jan-2018 18:49|