C++ If 语句,从 else 开始重复

标签 c++ loops if-statement

刚在大学开始使用 C++,所以我决定尝试使用 C++ 做一个经典的“商店项目”。

我只是想知道是否有任何方法可以从 else 中重复 if 语句。例如,在代码中,我询问用户是否愿意帮助浏览商店,如果他们回答是,那么它会向他们显示选项,如果他们回答否,那么它将继续执行代码,但是如果不是,或者不,那么代码会告诉用户它无法理解用户。

我想问的是,我能否让用户再次输入值并在不使用循环的情况下重新运行 if 语句,还是我必须使用循环?

代码如下:

cin >> help;
if (help == "Yes" || help == "yes")
{
    cout << "These are out current sections that you are able to browse:" << endl;
    cout << "-Offers and Deals (1) \n-Computing (2) \n-Console (3) \n-Audio (4) \n-Electronic Displays (5) \n-Cabling (6) \n-General Accessories (7)" << endl;
}
else if (help == "No" || help == "no")
{
    cout << "You have chosen not to look at our browsing list." << endl;
}
else
{
    cout << "Sorry the system does not understand what you have entered. \n Please use full English (Yes/No)." << endl;

}

如果有人能帮我解决这个问题,那就太好了。 我知道它的简单代码和可能更有效的方法,只需使用我目前在大学教授的方法。

提前致谢。

最佳答案

without using a loop, or do I have to use a loop?

有很多方法可以在不使用循环的情况下实现这一点,但循环正是允许您在条件为真时重复一段代码的结构。

这明确表达了您的意图并实现了您想要的结果。

void menu()
{
    while (true)
    {
        int i; std::cin >> i;

             if (i == 0) { action0(); }
        else if (i == 1) { action1(); }
        else if (i == 2) { break; /* Return to caller */ }
        else             { /* Invalid selection, retry */ }
    }
}

另一个合理的解决方案是使用递归。示例:

void menu()
{
    int i; std::cin >> i;

         if (i == 0) { action0(); }
    else if (i == 1) { action1(); }
    else if (i == 2) { return; /* Return to caller */ }
    else             { menu(); /* Invalid selection, retry */ }
}

但是,与循环相比,这可能有几个缺点。引用 François Andrieux来自评论:

Recursion is a reasonable alternative if loops can't be used, but it's worth mentioning the drawbacks. For example, there may be a limit to the number of times you can recur if tail call optimization doesn't come into play. If it does, then you essentially have a hidden loop. It's also worth mentioning that you can't do this with main. It's a mistake many beginners make when they first discover recursion.

关于C++ If 语句,从 else 开始重复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52667809/

相关文章:

Java - 验证一系列字母之间的字符串

php - 选择要运行的数据库连接

python-2.7 - 有没有比这更好的方法来实现强化学习的 Softmax Action 选择?

c++ - 当 STL 容器抛出异常时,如何找出确切的条件?

c++ - 对记录数组进行快速排序(结构)

c++ - 需要帮助以避免沮丧

if-statement - Struts 2 如果标签 : test with a constant

c++ - 采用 vector 参数的函数模板回文

Python:While循环不会终止

list - Ansible - 在一系列列表上依次循环