不幸的是,你並沒有真正表現出你正在使用的代碼,而是一些僞代碼。因此,很難說出你實際想要做什麼。然而,從我的問題和僞碼的描述來看,我懷疑問題的根源在於你不檢查輸入,也不會將數據流恢復到合理的狀態!要閱讀菜單選項,您可能想要使用類似於此的代碼:
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()
其餘
可能還有其他的問題,你的菜單,但沒有看到具體的代碼,我覺得這是很難說的具體問題是什麼。