codescracker


c++

C++ Program to Count Word in Sentence



« Previous Program Next Program »


Count Word in Sentence in C++

To count total number of words used in any sentence in C++ programming, you have to ask to the user to enter the sentence. Now to count total number of words present in the string, search for spaces, if found then increase a variable say countw (contains the occurrence of word) by 1 and continue to check for next space, to count the total number words present in the sentence as shown here in the following program.

C++ Programming Code to Count Word in Sentence

Following C++ program ask to the user to enter/write a sentence, to count the total number of words in the sentence, then display the result on the screen. This is a simple program which will count the words of simple sentence:

/* C++ Program - Count Word in Sentence */
		
#include<iostream.h>
#include<conio.h>
#include<string.h>
void main()
{
	clrscr();
	char strs[100], countw=0, strw[15], i;
	cout<<"Write a sentence : ";
	gets(strs);
	int len=strlen(strs);
	for(i=0; i<len; i++)
	{
		if(strs[i]==' ')
		{
			countw++;
		}
	}
	cout<<"Total number of words in the sentence is "<<countw+1;
	getch();
}

When the above C++ program is compile and executed, it will produce the following result:

C++ program count number words sentence

Same Program in Other Language

You may like the same program in other programming languages:


« Previous Program Next Program »



Tools
Calculator

Quick Links
Signup - Login - Give Online Test