刚在大学开始使用 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/