C++ Program to Count the Number of Vowels and Consonants in a String

1. Introduction

In many text-processing tasks, there might be a need to distinguish or count the occurrences of specific types of characters, like vowels and consonants in a given string. In this blog post, we will discuss a C++ program that achieves this by counting the number of vowels and consonants in a string.

2. Program Overview

Our approach will involve iterating over each character of the string and checking whether it's a vowel or a consonant. For simplicity, we'll consider the English alphabet, and the vowels are 'A', 'E', 'I', 'O', and 'U' (and their lowercase counterparts).

3. Code Program

#include <iostream>
#include <cctype>  // Needed for the tolower function
using namespace std;

int main() {
    string str;  // String to store user input
    int vowels = 0, consonants = 0;  // Counters for vowels and consonants

    cout << "Enter a string: ";
    getline(cin, str);  // Get the entire line of input including spaces

    // Loop through each character in the string
    for (char c : str) {
        // Check if the character is an alphabet (ignores digits, punctuation, etc.)
        if (isalpha(c)) {
            c = tolower(c);  // Convert the character to lowercase for uniformity in comparison

            // Check if the character is a vowel
            if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u') {
                vowels++;  // Increment the vowels count
            } else {
                consonants++;  // If not a vowel, increment the consonants count
            }
        }
    }

    // Display the results
    cout << "Number of vowels: " << vowels << endl;
    cout << "Number of consonants: " << consonants << endl;

    return 0;  // End of the program
}

Output:

Enter a string: Java Guides
Number of vowels: 5
Number of consonants: 5

4. Step By Step Explanation

1. We first take a string as input from the user.

2. We then iterate over each character of the string using a range-based for loop.

3. We use the isalpha function to check if the current character is an alphabet (ignoring digits, punctuation marks, etc.).

4. If the character is an alphabet, we convert it to lowercase using the tolower function to ensure our checks for vowels are case-insensitive.

5. We then check if the character is a vowel. If it is, we increment the vowels counter. Otherwise, we increment the consonants counter.

6. Finally, we display the counts of vowels and consonants in the string.

Comments