C ++ If语句,从else重复

时间:2018-10-05 14:26:47

标签: 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;

}

如果有人可以帮助我,那就太好了。 我知道它的简单代码以及可能有很多更有效的实现方法,只是使用了到目前为止大学所教授的ive方法。

谢谢。

1 个答案:

答案 0 :(得分:4)

  

不使用循环,还是我必须使用循环?

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

这可以明确表达您的意图并达到您想要的结果。

before removing it save those records in another ArrayList say BackupArrayList then Remove it as below
    if (recyclerList.size() > 4) {
        for (int i = 0; i < 4; i++) {
            BackUpArrayList.add(recyclerList.get(i));
            recyclerList.remove(i);
        }
        recyclerAdapter.notifyDataSetChanged();
    }

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

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 */ }
    }
}

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

  

如果不能使用循环,则递归是一个合理的选择,但是值得一提的缺点。例如,如果没有进行尾部调用优化,则可以重复的次数可能会受到限制。如果是这样,那么您实际上就具有一个隐藏循环。还值得一提的是,您无法使用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 */ } } 执行此操作。许多初学者第一次发现递归时会犯错。