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

[841 views]


In this tutorial we will learn how we can count the number of words in a sentence using C++. This type of program is 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 gets 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 World Total Number of words in Given Sentence is: 3
        

Algorithm Logic Test

Our Quiz prepared by Experts Helps you identify your knowledge in Algorithms. Everyone should atleast attempt this Quiz Once. 



Comments



Recommended Book Deals Ends in

Download 101 Ready to Use Excel Formulas ebook
Download Python All in One for Dummies ebook



Search
Online Games
Play 2048 Game Online and Relax.
Play 2048 Game Online

Search Tags

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

    Count number of words using C++

    Count number of words in a string