How to count the number of words in a sentence using C++

(175 Views)


In this tutorial we will learn how we can count the number of words in a sentence using C++. This type of program often asked in Job and Examinations. With the help of this program you will learn about for loop, if satement and the use of strings in C++. When you run the program you need to input a sentence and the for loop will search the space in the sentence. When it get any space it increases the value of the variable countword by 1 and thus the program count words in any given sentence.

How to count the number of words in a sentence using C++

C++ Program To Count Words In A Sentence:

#include<iostream.h> #include<conio.h> #include<string.h> #include<stdio.h> void main() { clrscr(); char strs[100], countword=0, strword[15]; int i, len; cout<<"Write any Sentence: "; gets(strs); len=strlen(strs); for(i=0; i<len; i++) { if(strs[i]==' ') { countword++; } } cout<<"Total Number of words in Given Sentence is: "<<countword+1; getch(); }

Output:

Write any Sentence: Welcome To Solutionfactory Total Number of words in Given Sentence is: 3

Solution Worked 0 UpvotesUpvote

        

Solution Didn't Worked 0 DownvotesDownvote

        


Comments



Search


Play 2048 Game Online

Play Duckhunt Online
Search Tags

    C++ program to calculate number of words in a sentence

    Count number of words using C++