Count the vowels in a string

Description: Count the vowels and the consonants in "Learn C++ Programming".

Hint:

  • Use std::isalpha and look for the letter in "aeiou".

Solution

#include <cctype>
#include <iostream>
#include <string>

int main() {
    std::string text = "Learn C++ Programming";
    int vowels = 0, consonants = 0;
    for (unsigned char c : text) {
        if (!std::isalpha(c)) continue;
        if (std::string("aeiou").find(static_cast<char>(std::tolower(c))) != std::string::npos) vowels++;
        else consonants++;
    }
    std::cout << "Vowels: " << vowels << ", consonants: " << consonants << '\n';
}
Output

Vowels: 5, consonants: 12

How it works

  • Spaces, + signs and other characters are skipped with continue.

Read C++ Strings.


Learn more about the similar topics:
Tutorials
No Content Found.
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.