Count the Number of Vowels in a String in C++
In this exercise, you will write a C++ function that counts how many vowels are present in a given string. Vowel detection is a common task in string manipulation, text analysis, and natural language processing.
The function should be able to handle both lowercase and uppercase vowels, and return the total count found. By completing this task, you'll reinforce your understanding of loops, conditionals, and string traversal in C++.
This is a beginner-friendly task that builds foundational logic used in more advanced textual data operations.
Implementation Details
1. Traversal
We use a range-based for loop to visit every character (char ch) in the string from beginning to end.
2. Normalization
Using tolower() allows us to check only for 'a, e, i, o, u' without needing to write separate logic for uppercase letters.
3. The Counter
A simple integer variable acts as an accumulator, incrementing by 1 every time the condition (is it a vowel?) is met.
Logic Tip:
Always check if the array is empty before accessing arr[0]. In professional environments, accessing index zero of an empty array can cause undefined behavior or program crashes.
Objective
- 1. Define a function that takes a
stringas a parameter. - 2. Loop through each character of the string.
- 3. Check if the character is a vowel (a, e, i, o, u) regardless of case.
- 4. Return the total count and display it in the console.
Example C++ Exercise
#include <iostream>
#include <string>
using namespace std;
// Function to count the number of vowels in a string
int countVowels(string text) {
int count = 0; // Initialize counter
// Loop through each character in the string
for (char ch : text) {
// Convert to lowercase for easier comparison
ch = tolower(ch);
// Check if the character is a vowel
if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') {
count++; // Increment if a vowel is found
}
}
return count;
}
int main() {
string input;
// Prompt the user to enter a string
cout << "Enter a string: ";
getline(cin, input); // Read the full line (including spaces)
// Call the function and display the result
int vowels = countVowels(input);
cout << "Number of vowels in the string: " << vowels << endl;
return 0;
}
Example Output:
Number of vowels in the string: 3