C++:检查用户输入是否是字符 A、W 或 D 之一

C++: Checking if user input is one of the characters A, W, or D

在Python我能做到:

char_choice = input("What is your character choice? Please enter A, W or   D.")
while char_choice.lower() not in ["a", "w", "d"]:
    char_choice = input("You entered an incorrect character. Please try 
    again:")

有没有办法在 C++ 中重复第 2 行?我已经尝试了很多方法,但它不起作用,所以我知道我做错了什么:

    char classificationCode;
    cin >> classificationCode;
    while (classificationCode != "b" || classificationCode != "B" ||     classificationCode != "d" || classificationCode != "D" || classificationCode != "w" || classificationCode != "W");

您正在根据字符串检查字符,您试过了吗

classificationCode != 'b'

最接近 Python 的是(在 C++11 中):

std::unordered_set<char> valid = {'a', 'w', 'd'};
while (!valid.count(tolower(classificationCode))) {
    cout << prompt;
    cin << classificationCode;
}

虽然将逻辑放在函数中并仅使用 switch:

并没有错
while (!isValidClassification(classificationCode)) {
    cout << prompt;
    cin >> classificationCode;
}

bool isValidClassification(char code) {
    switch (tolower(code)) {
    case 'a':
    case 'w':
    case 'd':
        return true;
    default:
        return false;
    }
}

在 C++03 中,没有 unordered_set 或列表初始化,因此您必须像这样声明有效:

std::set<char> valid;
valid.insert('a');
valid.insert('w');
valid.insert('d');

如果您想检查字符序列是否包含字符,您可以使用该代码:

(std::string("awd").find(std::tolower(ch)) != std::string::npos)

当然有很多方法可以实现这一点:使用向量而不是字符串,使用 C++11 <locale> 而不是 C 中的 ctype 等

您可以将 classificationCode 字符转换为小写字母 tolower():

char lowerCode = tolower(classificationCode);

注意需要先包含"ctype.h"头文件!

之后,您应该正确设置 while 条件。我猜您是在 do-while loop 中执行此操作。如果要确保用户输入的是 "b"、"d" 或 "w",则需要使用逻辑与 (&&)。你最后的条件应该是:

// ...
while (lowerCode != 'b' && lowerCode != 'd' && lowerCode != 'w')

您应该将 || 更改为 &&,或者您可以尝试
while (!(classificationCode == 'b' || classificationCode == 'B' || ...))
不要忘记将 "" 更改为 '',因为 classificationCode 的类型是 char。
如果你想降低,试试 std::ctype::tolower(),包括