C++ Example - Determine Vowel/Consonant

C++ Examples

English has 26 letters. The vowels only include the five letters a, e, i, o, u, and the rest are consonants. y is a semi-vowel and semi-consonant letter, but in English it is always treated as a consonant.

Example 1

#include<iostream> using namespace std; int main() { char c; bool ischar; int isLowercaseVowel,isUppercaseVowel; cout<<"Enter a letter:"; cin>>c; ischar=((c>='a'&&c<='z')||(c>='A'&&c<='Z')); if(ischar) { //Lowercase vowel isLowercaseVowel=(c=='a'||c=='e'||c=='i'||c=='o'||c=='u'); //Uppercase vowel isUppercaseVowel=(c=='A'||c=='E'||c=='I'||c=='O'||c=='U'); //if statement check if(isLowercaseVowel||isUppercaseVowel) cout<<c<<"is a vowel"; else cout<<c<<"is a consonant"; } else { cout<<"The input is not a letter."; } return 0; }

The execution output of the above program is:

输入一个字母: G
G 是辅音

Example 2

#include <iostream>
using namespace std;

bool isVowel(char letter) {
    // Convert the letter to lowercase
    letter = tolower(letter);

    // Determine whether the letter is a vowel
    if (letter == 'a' || letter == 'e' || letter == 'i' || letter == 'o' || letter == 'u') {
        return true;
    } else {
        return false;
    }
}

int main() {
    char letter;
    cout << "Please enter a letter: ";
    cin >> letter;

    if (isVowel(letter)) {
        cout << letter << " is a vowel." << endl;
    } else {
        cout << letter << " is a consonant." << endl;
    }

    return 0;
}

In the above code, we defined a function isVowel, which takes a letter as a parameter and returns a boolean value. In the function, we convert the letter to lowercase and use a conditional statement to determine whether it is a vowel. If the letter is a vowel, the function returns true; otherwise, it returns false. In the main function, we accept the letter entered by the user, call the isVowel function to make the determination, and then output the corresponding result.

C++ Examples

other extensions