不幸的是,你并没有真正表现出你正在使用的代码,而是一些伪代码。因此,很难说出你实际想要做什么。然而,从我的问题和伪码的描述来看,我怀疑问题的根源在于你不检查输入,也不会将数据流恢复到合理的状态!要阅读菜单选项,您可能想要使用类似于此的代码:
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");
}
}
这只是输入基本上如何的粗略布局。它可能被封装成一个函数(在这种情况下,你希望从一个封闭的输入中以不同的方式退出,可能使用一个异常或一个特殊的返回值)。他的主要部分是
- 恢复流回到良好的状态使用
std::isteam::clear()
- 跳过坏输入,在这种情况下使用
std::getline()
与std::string
;你也行只是std::istream::ignore()
其余
可能还有其他的问题,你的菜单,但没有看到具体的代码,我觉得这是很难说的具体问题是什么。