首页 > 解决方案 > 您可以在开关中使用 OR 吗?

问题描述

你可以在 switch case 中使用 OR 运算符吗?我试图从用户输入检查中删除区分大小写(所以可能有更好的方法来做到这一点,毕竟我是初学者),这当然导致我的开关情况加倍(不包括默认情况)。此时使用 if/else 会更好,还是有办法检查案例中的不同条件?

我的代码,如果有帮助:

    case 'Y':
    case 'y':
        cout << "Good, we will check later to ensure your opinion is unchanged." << endl;
        break;
    case 'N':
    case 'n':
        cout << "Open your window tonight, unlock the door, take sleep medication, and ignore any noises in your room." << endl;
        break;
    default:
        cout << "Not an answer... think you can play games with me? I'll give you worse than the lemon haters, you'll be better off killing yourself before I take matters into my own hands." << endl;

标签: c++

解决方案


如果您不打算区分字母是小写还是大写,那么最好的解决方案是将您的开关变量“转换”为小写/大写。这样,您将摆脱不必要的案例,并在将来实施新案例时节省一些时间。

根据您的决定,您可以选择std::tolowerstd::toupper

switch (std::tolower(x)) {
    case 'y':
        std::cout << "answer1" << std::endl;
        break;
    case 'n':
        std::cout << "answer2" << std::endl;
        break;
    default:
        std::cout << "answer3" << std::endl; 
        break;
}

回答您关于 OR 语句用法的问题 - 它不适用于char. 所有字符都用一些整数(来自 ASCII 表的值)定义,这意味着 egy具有 value 121,而Yhas 89

让我们看一下表达式case 'y' || 'Y':从返回的值'y' || 'Y'实际上是1。这怎么可能?1如果至少有一个参数不是0,则OR 语句返回,0否则返回。这是计算值的方式:

case 'y' ||  'Y'    =>    case 121 || 89    =>    case 1

可悲的是,既不是y也不是ASCIIY定义的,因此 switch 将使用该输入的大小写。1default


推荐阅读