Program to count the number of words, characters, alphabets, vowels, consonants and digit in a line of text
Written by
Understanding the problem:
The given question wants us to write an efficient C++ program that takes a string input from the user and displays the number of words, characters, alphabets, vowels, consonants and digits in that given string.
Approaching the problem:
A string is an array of characters, therefore, the number of characters in a string is equal to the string length. Further, we have library functions in C++ to check whether a character is an alphabet or a digit.
An alphabet can either be a vowel or a consonant, so, if an alphabet isn’t a vowel then it is a consonant.
To count the number of words we can check when we encounter a ‘space’ or ‘end of line (\0)’ character. As we encounter any of these we will increment our word count by one.
Algorithm:
- First, we will input a string from the user and store it in a string variable str.
- Then we will access str character by character with the help of a for loop
- First, we will check if the current character is alphabet with the help of “isalpha()” function. If yes we will further use a nested if condition to check if it’s a vowel by comparing it with the five vowels both upper case and lower case.
- Next, we will check for digit with the help of “isdigit()” function.
- At last, we will check for ‘space’ and ‘\0’ to count the number of words.
Code:
#include <iostream>
#include <string> //for using string data type and its functions
#include <cstdio> //for using getline function
#include <ctype.h > //for using isalpha, isdigit function
using namespace std;
int main(){
string str; //inputting the string and setting all the
int words = 0, ch = 0, dig = 0, alph = 0, vow = 0, cons = 0; // parameters as zero
cout << "Enter a string\n";
getline(cin, str);
ch = str.length(); //setting number of characters equal to the //string length
for (int i = 0; i <= str.length(); ++i) //accessing the string character by character
{
if (isalpha(str[i])) //checking for alphabets
{ ++alph;
if (str[i] == 'A' || str[i] == 'a' || str[i] == 'E' || str[i] == 'e' || str[i] == 'I' || str[i] == 'i' || str[i] == 'O' || str[i] == 'o' || str[i] == 'U' || str[i] == 'u') //checking for vowels
++vow;
else
++cons; //if not vowel then it must be a consonant
}
else if (isdigit(str[i])) //checking for digits
++dig;
if (str[i] == ' ' || str[i] == '\0') //counting the umber of words
++words;
}
cout << "Number of words=" << words << "\n";
cout << "Number of alphabets=" << alph << "\n";
cout << "Number of vowels=" << vow << "\n";
cout << "Number of consonants=" << cons << "\n";
cout << "Number of digits=" << dig << "\n";
cout << "Number of characters=" << ch << "\n";
return 0;
}
Output
Enter a string
Hello World!
Number of words=2
Number of alphabets=10
Number of vowels=3
Number of consonants=7
Number of digits=1
Number of characters=12