Tak*_*nie 2 c++ variables loops while-loop
我正在开发一个小型数据库项目.我已经创建了一个带有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;
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
编辑:另一个例子,更多变量.
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;
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
最好的做法是将该while循环提取到函数中而return不是Loop = 1;.这将是明确的流量控制,易于阅读和维护.例如:
void mainMenuLoop(vector<Employee>& firmEmployees, vector<Intern>& firmInterns) {
for(;;) {
cout << "\n\n================ EMPLOYEE DATABASE ================\n\n";
cout << " HIRE NEW EMPLOYEE (1)\n";
cout << " MANAGE EMPLOYEES (2)\n";
cout << " HIRE NEW INTERN (3)\n";
cout << " MANAGE INTERNS (4)\n";
cout << " EXIT (5)\n";
cout << " Choose option... " << flush; // Must flush here.
int option = -1; // Assign a wrong initial option.
cin >> option;
switch (option) {
case 1:
hireEmployee(firmEmployees);
break;
case 2:
employeeMenu(firmEmployees);
break;
case 3:
hireIntern(firmInterns);
break;
case 4:
internMenu(firmInterns);
break;
case 5:
return;
default:
cout << "\n---Wrong input!---" << endl;
clearInput(); // cleaning cin
break;
}
}
}
void mainMenu() {
vector<Employee> firmEmployees;
vector<Intern> firmInterns;
mainMenuLoop(firmEmployees, firmInterns);
}
Run Code Online (Sandbox Code Playgroud)
还要注意,在
int option;
cin >> option;
Run Code Online (Sandbox Code Playgroud)
如果cin >> option失败,则option保留其原始的不确定值,这可能是可用选项之一.为它分配一个不是有效选项的初始值更安全,比如-1.