【问题标题】:C++: Checking if user input is one of the characters A, W, or DC++:检查用户输入是否是字符 A、W 或 D 之一
【发布时间】:2015-03-28 21:41:20
【问题描述】:

在 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");

【问题讨论】:

    标签: python c++ validation loops conditional-statements


    【解决方案1】:

    你正在检查一个字符和一个字符串,你试过了吗

    classificationCode != 'b'
    

    【讨论】:

    • 确实如此。否则,您将根据与 char 'b' 等效的整数值检查字符串“b”的地址
    • @RichardGreen 是的,不知道有多少次我花了一个小时跟踪一个错误,却发现它是一个字符串而不是一个字符。
    • 虽然检查字符而不是字符串是正确且重要的,但在 while 循环中,其中一个答案将始终为 True,因此它将永远重复
    • @Maor 我没有检查他的整个循环,我只是指出主要问题是他将字符与字符串进行比较。
    • 这绝对有帮助。我必须注意那些双引号和单引号哈哈......
    【解决方案2】:

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

    char lowerCode = tolower(classificationCode);
    

    注意,需要先包含“ctype.h”头文件!

    之后,你应该让你的 while 条件正确。我猜你是在do-while loop 里面做的。如果要确保用户输入“b”、“d”或“w”,则需要使用逻辑与 (&&)。你最后的条件应该是:

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

    【讨论】:

      【解决方案3】:

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

      【讨论】:

        【解决方案4】:

        最接近 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');
        

        【讨论】:

          【解决方案5】:

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

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

          当然有很多方法可以实现这一点:使用向量代替字符串,使用 C++11 &lt;locale&gt; 代替 C 中的 ctype,等等。

          【讨论】:

          • 他没有检查一个序列是否包含一个字符,他只是想检查一个字符与另一个字符,所以正常的 != 应该可以正常工作。
          • @DylanLawrence 但这就是 Python 中的 in 的工作方式。这也是避免多个 != 的 Pythonic 方式。
          • 啊,我明白了……我在倒读你的代码。 Python确实是这样的,但是对于学习C++的人来说,这可能不是最好的选择。
          • @DylanLawrence,这就是 C++ 的精髓 :)。在 Python 中,有一种“Pythonic”方式可以做到这一点,还有一些建议避免使用。在 C++ 中,您可以使用 C 方式使用 != 'ch' 或 switch(见下文)或跳转表,使用 Python 方式,就像我建议的那样,甚至更糟 - 使用模板元编程生成条件。
          • "模板元编程" 走开邪恶恶魔!
          猜你喜欢
          • 2014-03-15
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-11-22
          • 2016-02-10
          • 1970-01-01
          • 2012-08-17
          • 1970-01-01
          相关资源
          最近更新 更多