C Plus Plus
Program to count letters and words
Counting
the letters and words in a C++ program is a very simple and funny task. In this
program we are going to develop a program in C++ which will count the letters
and words in a phrase or a paragraph.
User
will enter the phrase, sentence or a paragraph and this C++ program will count
the letters and words and display them on screen.
Practical
use of word counter
You
have probably used the Microsoft Word. In Microsoft Word, there is
functionality to count the words. These counted words are displayed on screen
at left down corner, as you type the words. The same job has been done by this
program. It not only counts the words but also letters. It is possibility that
this program will be soon integrated in the MS Word.
C++ Program
Code of Word and Letter Counter
//softoset.blogspot.com
#include<iostream>
#include<conio.h>
using
namespace std;
int
main()
{
int
cwd=1;
int
clet=0;
char
ch='a';
cout<<"Enter
a Phrase\n";
while(ch!='\r')
{
ch=getche();
if(ch==' ')
cwd++;
else
clet++;
}
cout<<"\n\nWords
="<<cwd<<"\nLetters ="<<clet-1;
return
0;
}
Output of
Letter and Word Counter Program in C++
We
have run this code on our Dev C++, On execution of this code we have got the
following output.
Look
at the output you can see that the program has counted the exact and accurate
number of words and the letters.
Logic of
Letter and Word Counter Program
There
is a simple logic of this program. In main function, we have declared the two
variables cwd to count words and clet to count letters. We have declared
another variable ch of character data type to take the phrase or sentence form
user. We have then use a while loop, which will take the characters unless the
‘\r’ is pressed, which is used in programming for the Enter key. Then in while
loop ch=getche(); is used for the input and echoes the characters on screen. It
is build in function in the library of conio.h so for using it you need to
insert the conio.h header file. Then we have put a condition that if ‘ ‘ means
a space bar then increase a word and else increase a letter.
Finally
when user will press the enter key, while loop will terminate and out of while
loop statement will print the number of letters and words on the screen. That’s
it.
Thanks
for learning form this site. Keep practicing to be perfect.
Post a Comment
Feel Free to Comment Us