循环C++ 'else'

C++ 'else' in loops

本文关键字:else C++ 循环      更新时间:2023-10-16

在C++中,我在执行循环时遇到了一个问题。我只知道我在工作中忽略了一个明显的解决方案。这里有一个例子可供参考:

#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
string loop();
int main()
{
    string answer;
    do
    {
        cout << "Do you wish to be asked this question again?: ";
        cin >> answer;
        if (answer == "no" || answer == "No" || answer == "NO")
            cout << "As you wish";
        else if (answer == "yes" || answer == "Yes" || answer == "YES")
            cout << "";
        else
        {
            cout << "You didn't answer yes or non";
            loop();
        }
    }while (answer == "yes" || answer == "Yes" || answer == "YES");
    return 0;
}
string loop()
{
        string answer;
        cout << "Do you wish to be asked this question again?: ";
        cin >> answer;
        if (answer == "no" || answer == "No" || answer == "NO")
            cout << "As you wish";
        else if (answer == "yes" || answer == "Yes" || answer == "YES")
            cout << "";
        else
        {
            cout << "You didn't answer yes or non";
            loop();
        }
        return answer;
}

当我在循环中执行If else时,当涉及到else部分时,我遇到了一个问题。我似乎不知道如何显示告诉用户有错误的东西,然后重新运行相同的序列。例如,在我包含的程序中,当用户输入"是"或"否"以外的内容时,我不确定如何显示错误语句,然后将其循环回顶部,以便它再次提问。

您应该使用while循环。

string answer;
while ( (answer != "yes") && (answer != "no") ) {
    cout << "Do you wish to be asked this question again?: ";
    cin >> answer;
    if (answer == "no" || answer == "No" || answer == "NO") {
        cout << "As you wish";
        break;
    }
    if (answer == "yes" || answer == "Yes" || answer == "YES") {
        cout << "";
        break;
    }
}

问题不在于循环;问题是你把逻辑搞得一团糟。解决方案不是修复循环的方法,而是理顺逻辑的方法。

一个比看起来有用得多的简单技巧是将循环与你在循环中所做的事情完全分离:

// This function does something, then returns a boolean value
// to indicate whether or not you should continue looping.
bool do_something();
int main()
{
    bool continue_looping = true;
    while (continue_looping) {
        continue_looping = do_something();
    }
}

现在,您实现do_something()的方式不必担心实际执行循环;在这方面,它唯一的责任是返回一个值,指示循环是否应该继续。

您只需要一个do-while循环。。。

#include<iostream>
#include<string>
#include<algorithm>
using namespace std;
int main()
{
    string ans{""};
    transform(ans.begin(), ans.end(), ans.begin(), ::tolower); // convert string to lower case
    do {
        cout << "Do you wish to be asked this question again? ";
        cin >> ans;
        if (ans == "no") {
            cout << "As you wish.";
        } else
        if (ans == "yes") {
            cout << "";
        }
        else {
            cout << "You didn't answer yes or no." << endl;         
        }
    } while (ans != "yes" && ans != "no");  
    return 0;
}

注意,转换算法将字符串转换为小写,以避免yesno的拼写变化。