gpt4 book ai didi

c++ - 如何使用循环显示菜单并重新提示输入?

转载 作者:行者123 更新时间:2023-11-28 08:11:48 25 4
gpt4 key购买 nike

我想要一个接受用户输入的菜单显示。但是,我希望用户能够返回到菜单的开头以重新选择选项。

while(end != 1) {
display menu options
prompt user for input
if(input == x) {
do this
}
else
do that
}

然后,我希望它跳回循环的开头并再次提出问题。如果不在屏幕上创建菜单打印的无限循环,我如何才能做到这一点?

最佳答案

不幸的是,您并没有真正展示您正在使用的代码,而是展示了一些伪代码。因此,很难说出您实际想要做什么。然而,根据你的问题和伪代码的描述,我怀疑问题的根源是你没有检查你的输入,也没有将流恢复到一个相当好的状态!要阅读菜单选择,您可能需要使用类似于此的代码:

int choice(0);
if (std::cin >> choice) {
deal with the choice of the menu here
}
else if (std::cin.eof()) {
// we failed because there is no further input: bail out!
return;
}
else {
std::string line;
std::cin.clear();
if (std::getline(std::cin, line)) {
std::cout << "the line '" << line << "' couldn't be procssed (ignored)\n";
}
else {
throw std::runtime_error("this place should never be reached! giving up");
}
}

这只是输入的基本外观的粗略布局。它可能会被封装到一个函数中(在这种情况下,您希望以某种不同的方式从关闭的输入中退出,可能使用异常或特殊的返回值)。他的主要部分是

  1. 使用 std::isteam::clear() 将流恢复到良好状态
  2. 跳过错误的输入,在本例中使用带有 std::stringstd::getline();你也可以只是 std::istream::ignore() 该行的剩余部分

您的菜单可能还有其他问题,但如果没有看到具体代码,我认为很难说出具体问题是什么。

关于c++ - 如何使用循环显示菜单并重新提示输入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8865208/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com