我正在开展一个项目,需要显示一些菜单,其中一些菜单有子菜单。到目前为止我已经创建了一个函数,它返回用户选择的字符,问题是菜单之间的一对多次来回返回值是垃圾,它与cin
被刷新有关但我无法找到" spot"这是必须清除...
我在不同的地方尝试了cin.clear();
,结果好坏参半,我错过了什么?
输出:
#include <iostream>
#include <string>
#include <vector>
#include <exception>
#include <istream>
using namespace std;
char Menu() {
char ch;
//ch = NULL;
//cin.clear();
cout << "++++++++++++++++++++++++++++++++++++++++++++" << endl;
cout << "+ MAIN MENU +" << endl;
cout << "++++++++++++++++++++++++++++++++++++++++++++" << endl;
cout << "| 1. Enter a new contract. |" << endl;
cout << "| 2. Cancel an active conract. |" << endl;
cout << "| 3. Edit a cotract. |" << endl;
cout << "| 0. Exit |" << endl;
cout << "++++++++++++++++++++++++++++++++++++++++++++" << endl;
cin >> ch;
switch (ch) {
//cin.clear();
case '1':
return ch;
break;
case '2':
return ch;
break;
case '3':
//cin.clear();
cout << "++++++++++++++++++++++++++++++++++++++++++++++++++++++++++" << endl;
cout << "+ -== Edit a cotract ==- +" << endl;
cout << "++++++++++++++++++++++++++++++++++++++++++++++++++++++++++" << endl;
cout << " What would like to edit? |" << endl;
cout << " a) Cover amount. |" << endl;
cout << " b) Add a family memeber.(Applyes to Health insurances) |" << endl;
cout << " 0. Return |" << endl;
cout << "++++++++++++++++++++++++++++++++++++++++++++++++++++++++++" << endl;
cin >> ch;
if(ch == '0') {
//cin.clear();
Menu();
} else if((ch >= 'a') && (ch <= 'b')) {
return ch;
} else {
cout << "Wrong input ! ! !" << endl;
Menu();
return ch;
}
break;
case '0':
cout << "Exiting bye!" << endl;
break;
default:
cout << "Wrong input ! ! !" << endl;
Menu();
break;
}
}
int main() {
char choise;
choise = Menu();
cout << "selected: " << choise << endl;
system("PAUSE");
return 0;
}
答案 0 :(得分:2)
default:
cout << "Wrong input ! ! !" << endl;
Menu();
break;
您调用了另一个Menu()
来获取输入,但没有将其返回值返回给调用者main()
。
将其更改为return Menu();
。