c++ - 您可以在开关中使用 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;
解决方案
如果您不打算区分字母是小写还是大写,那么最好的解决方案是将您的开关变量“转换”为小写/大写。这样,您将摆脱不必要的案例,并在将来实施新案例时节省一些时间。
根据您的决定,您可以选择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 表的值)定义,这意味着 egy
具有 value 121
,而Y
has 89
。
让我们看一下表达式case 'y' || 'Y'
:从返回的值'y' || 'Y'
实际上是1
。这怎么可能?1
如果至少有一个参数不是0
,则OR 语句返回,0
否则返回。这是计算值的方式:
case 'y' || 'Y' => case 121 || 89 => case 1
可悲的是,既不是y
也不是ASCIIY
定义的,因此 switch 将使用该输入的大小写。1
default
推荐阅读
- flutter - Flutter CupertinoTabBar 显示 CupertinoTabView like Share Page on Instagram
- javascript - 如何获取日期时间选择器并将其转换为服务器格式(toISOString)
- c++ - 找不到 -llibmysqld Collect2.exe:错误:ld 返回 1 个退出状态
- assembly - 如何在 ARM 汇编语言中使用 CPUlator 从用户那里获取输入
- javascript - 如何在javascript中保存函数的结果?
- vb.net - 如何将 SSL 密码套件添加到 HttpWebRequest VB.NET?
- elixir - Elixir 语法错误:创建地图时出现无效令牌错误
- flutter - 是否可以在元素的属性中添加 json?
- python - Django 数据库缓存查询集方法
- typescript - 测试驱动开发 - 使用 TypeScript 时测试输入参数