可以在 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;
最佳答案
如果您不打算区分字母是小写还是大写,那么最好的解决方案是将您的 switch 变量“转换”为小写/大写。这样,您将摆脱不必要的案例,并在将来实现新案例时节省一些时间。
根据您的决定,您可以选择 std::tolower
或 std::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 表的值)定义,这意味着例如y
的值为 121
,而 Y
的值为 89
。
让我们看一下表达式 case 'y' || 'Y'
:'y' || 返回的值“Y”
实际上是 1
。这怎么可能?如果至少一个参数不是 0
,则 OR 语句返回 1
,否则返回 0
。该值的计算方式如下:
case 'y' || 'Y' => case 121 || 89 => case 1
遗憾的是,y
和 Y
都没有在 ASCII 中定义为 1
,因此 switch 将使用 default
大小写使用该输入。
关于c++ - 可以在 switch 中使用 OR 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62293820/