c++ switch - 不评估并显示“条件始终为真”
我正在尝试是否可以在 switch 语句中使用“逻辑或”内部 case 子句。我在第一种情况下尝试了这种方法,当我在两种情况下输入“A”或“a”时,系统会一起跳过它。
# include <iostream>
using namespace std;
int main () {
/* prg. checks if the input is an vowel */
char ch;
cout << "please input a word to check if it is vowel or not" << endl;
cin >> ch;
switch (ch) {
case ('A'|| 'a') :
cout << "it is vowel" << endl;
break;
case 'E':
cout << "it is vowel" << endl;
break;
case 'I':
cout << "it is vowel" << endl;
break;
case 'O':
cout << "it is vowel" << endl;
break;
case 'U':
cout << "it is vowel" << endl;
break;
default:
cout << "it is not a vowel" << endl;
break;
}
有没有正确的方法在 case 子句中使用 or ?
谢谢你的帮助。
I was experimenting whether I can use "logical or" inside case clause for a switch statement. I tried this way for the first case and the system skipped it all together when I gave input as "A" or "a" in both the cases.
# include <iostream>
using namespace std;
int main () {
/* prg. checks if the input is an vowel */
char ch;
cout << "please input a word to check if it is vowel or not" << endl;
cin >> ch;
switch (ch) {
case ('A'|| 'a') :
cout << "it is vowel" << endl;
break;
case 'E':
cout << "it is vowel" << endl;
break;
case 'I':
cout << "it is vowel" << endl;
break;
case 'O':
cout << "it is vowel" << endl;
break;
case 'U':
cout << "it is vowel" << endl;
break;
default:
cout << "it is not a vowel" << endl;
break;
}
is there a proper way to use or inside the case clause ?
Thank you for the help.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
case('a'||'a')
应写为:如果它匹配
'a'
它将落在下一个case < /code>(除非有<代码>中断
之间)。在这种情况下,您可能需要将 All vowles组合:
请注意,某些编译器将通过
case
)。由于C ++ 17,如果您在案例中使用秋季,则可以使用 <代码> Fallthough 归因于您实际想要跌倒的这种警告。The
case ('A'|| 'a')
should be written as:If it matches on
'A'
it will fall through to the nextcase
(unless there's abreak
in between).In this case, you may want to combine all vowles:
Note that some compilers will issue a warning for fall through
case
s with statements in them (which is not the case above). Since C++17, if you use fall through cases, you can use thefallthrough
attribute to silence such warnings where you actually want a fall through.