C++ 检查字符是元音还是辅音程序

要理解本示例,您应该了解以下 C++ 编程 主题


五个字母a、e、i、o、u称为元音。除了这5个字母以外的所有其他字母都称为辅音。

此程序假定用户将始终输入一个字母。


示例:手动检查元音或辅音

#include <iostream>
using namespace std;

int main() {
    char c;
    bool isLowercaseVowel, isUppercaseVowel;

    cout << "Enter an alphabet: ";
    cin >> c;

    // evaluates to 1 (true) if c is a lowercase vowel
    isLowercaseVowel = (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u');

    // evaluates to 1 (true) if c is an uppercase vowel
    isUppercaseVowel = (c == 'A' || c == 'E' || c == 'I' || c == 'O' || c == 'U');

    // show error message if c is not an alphabet
    if (!isalpha(c))
      printf("Error! Non-alphabetic character.");
    else if (isLowercaseVowel || isUppercaseVowel)
        cout << c << " is a vowel.";
    else
        cout << c << " is a consonant.";

    return 0;
}

输出

Enter an alphabet: u
u is a vowel.

用户输入的字符存储在变量 c 中。

isLowerCaseVowelc 是小写元音时计算为true,在其他任何字符时计算为false

同样,isUpperCaseVowelc 是大写元音时计算为true,在其他任何字符时计算为false

如果isLowercaseVowelisUppercaseVowel都为true,则输入的字符是元音,否则该字符是辅音。

isalpha()函数检查输入的字符是否为字母。如果不是,则打印错误消息。


另请阅读

你觉得这篇文章有帮助吗?

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战