使用 "else if" 是否不需要在 while 循环中的每个条件后中断?

Does using "else if" eliminate the need for breaks after each condition in a while loop?

使用 "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.

是的,你可以。

提示:如果您想确定重构是否有效,您可以编写一个测试来检查代码是否正确。

代码做同样的事情,执行时间没有区别,所以它们是相似的。不过,在第一个代码片段中,您不需要最后一个 break 。但是,如果您想为您的案例设计一个好的样式,您应该考虑 switch 语句。

while(true){
   char c;
   cin >>c;

   switch (c) {
     case 'A': 
        // deal with char A
        break;
     case 'b':
        // deal with char b
        break;
     default:
        continue;
   }
     break;
}

对于带有字符串的 switch 语句,您可以检查一下:Evaluate a string with a switch in C++

我觉得 switch 语句更优雅。