使用“else if”是否可以消除while循环中每个条件之后的中断时间?输入正确的输入之一后,我想退出循环。
我的代码的第一个版本看起来像这样
string s;
string str;
while (true) {
cin >> s;
if (s == "a") {
str = "Apple";
break;
}
if (s == "b") {
str = "Banana";
break;
}
... more ifs ...
else {
cout << "Did not recognize input." << endl;
continue;
}
}
我可以将其更改为下面的代码而不会产生负面影响吗?对我来说,它更短,更漂亮。
string s;
string str;
while (true) {
cin >> s;
if (s == "a") str = "Apple";
else if (s == "b") str = "Banana";
else if (s == "c") str = "Cat";
... more else-ifs ...
else {
cout << "Did not recognize input." << endl;
continue;
}
break;
}
最佳答案
是的,那行得通。 else if
链确保仅else
大小写continue
循环,并且不击中else
大小写会触发break
。