【发布时间】:2018-11-17 16:34:15
【问题描述】:
我正在做一个小型数据库项目。我已经用switch() 函数创建了一个接口,它应该是调用函数并循环,直到我选择了“EXIT”选项。我通过将指定值设置为int Loop 变量来控制循环。以这种方式处理这种循环是一种好习惯吗?如果不是,那为什么?在其他函数中,当我有多个条件时,我甚至两次使用那种变量。也许我应该做不同的事情?如果我在这种情况下使用 try(), throw(), catch() 异常是否有意义,那么它会是什么样子?这是我的一段代码:
void mainMenu() {
vector<Employee> firmEmployees;
vector<Intern> firmInterns;
int Loop = 0;
while (Loop == 0) {
cout << endl << endl;
cout << "================ EMPLOYEE DATABASE ================" << endl << endl;
cout << " HIRE NEW EMPLOYEE (1)" << endl;
cout << " MANAGE EMPLOYEES (2)" << endl;
cout << " HIRE NEW INTERN (3)" << endl;
cout << " MANAGE INTERNS (4)" << endl;
cout << " EXIT (5)" << endl;
cout << " Choose option... ";
int option;
cin >> option;
if (option < 1 || option > 5 || !cin) {
cout << endl << "---Wrong input!---";
clearInput(); // cleaning cin
} else {
switch (option) {
default:
break;
case 1:
hireEmployee(firmEmployees);
break;
case 2:
employeeMenu(firmEmployees);
break;
case 3:
hireIntern(firmInterns);
break;
case 4:
internMenu(firmInterns);
break;
case 5:
Loop = 1;
break;
}
}
}
}
编辑:另一个例子,更多变量。
void fireEmployee(vector<Employee>& sourceEmployee) {
int repeat = 0;
while (repeat == 0) {
cout << "Enter ID to fire an employee: ";
int id;
cin >> id;
if (cin.fail()) {
clearInput();
cout << "ID number needed!" << endl;
} else {
int buf = 0;
for (auto &i : sourceEmployee) {
if (i.getID() == id) {
i.Fire();
i.setSalary(0);
cout << i.getName() << " " << i.getSurname() << " (" << i.getID() << ") has been fired" << endl;
buf = 1;
repeat = 1;
}
}
if (buf == 0) {
cout << "No employee with ID: " << id << endl;
}
}
}
}
【问题讨论】:
-
如果这是 1971 年和 computers looked like this,那么这种互动是可以预料的。这些天来,我们期待更好的东西。考虑编写一个命令行解释器,您可以在其中执行
hire bob或fire bob等操作。键入2是您在电话语音菜单上所做的。 -
@tadman 这可能是真的,但这并不是问题的真正答案。
-
该死的。很高兴我出生于 73 年。
标签: c++ loops variables while-loop