在C ++中在一行中初始化多个变量

时间:2018-09-27 18:26:19

标签: c++

这是我的程序代码,应该提示用户提供单个字母,然后报告该字母是元音还是辅音:

#include <iostream>
using namespace std;

int main() {
    cout << "input a single letter";
    int var; 
    cin >> var;
    int vowel = 'a','e','i','o','u';
    int consonant = 'b','c','d','f','g','h','j','k','l','m','n','p','q','r','s','t','v','w','x','y','z'
    if (var == vowel) {
        cout << "vowel";
    } else if (var == consonant) {
        cout << "consonant";
    } else if (var != vowel && var != consonant) {
        cout << "Error";
    }
    return 0;
}

我是C ++的新手,正试图了解为什么我收到一条错误消息。

1 个答案:

答案 0 :(得分:2)

对于您正在尝试的代码,此代码是完全错误的。您正在以int角色而不是char角色的形式读取输入。您没有正确初始化vowelconsonant变量,也没有正确地将var与它们进行比较。您不检查输入错误。您不处理大写字母。

请改用类似的方法

#include <iostream>
#include <cctype>
using namespace std;

int main() {
    cout << "input a single letter";
    char var; 
    if (cin >> var) {
        var = (char) ::tolower( (unsigned char)var );
        if ((var >= 'a') && (var <= 'z')) {
            if ((var == 'a') || (var == 'e') || (var == 'i') || (var == 'o') || (var == 'u')) {
                cout << "vowel";
            } else {
                cout << "consonant";
            }

            /* alternatively:
            switch (var) {
                case 'a':
                case 'e':
                case 'i':
                case 'o':
                case 'u':
                    cout << "vowel";
                    break;

                default:
                    cout << "consonant";
                    break;
            }
            */
        }
        else {
            cout << "Error";
        }
    }
    else {
        cout << "Input Error";
    }
    return 0;
}

或者:

#include <iostream>
#include <string>
#include <cctype>
using namespace std;

const string vowels = "aeiou";
const string consonants = "bcdfghjklmnpqrstvwxyz";

int main() {
    cout << "input a single letter";
    char var; 
    if (cin >> var) {
        var = (char) ::tolower( (unsigned char)var );
        if (vowels.find(var) != string::npos) {
            cout << "vowel";
        } else if (consonant.find(var) != string::npos) {
            cout << "consonant";
        } else {
            cout << "Error";
        }
    }
    else {
        cout << "Input Error";
    }
    return 0;
}