#include <iostream>
#include <string>
#ifndef en
#define en std::endl
#endif
using namespace std;
int login() {
//Basic login program
login:
string correctPass = "Love";
string attemptPass;
cout << "Please insert password" << en;
cin >> attemptPass;
if (attemptPass == correctPass) {
cout << "Access Granted" << en << en;
} else {
goto login;
}
return 0;
}
int main() {
// Everything below is main menu crap that I want to turn into a function that somehow allows goto statements
login();
mainMenu:
cout << en << "MAIN MENU" << en << en << "Payroll" << en << "Employees" << en << en;
string mainMenuOption;
cin >> mainMenuOption;
if (mainMenuOption == "Payroll" || "payroll") {
goto payroll; }
else if (mainMenuOption == "Employees" || "employees") {
goto employees; }
else {
goto mainMenu; }
payroll:
cout << "Fish";
return 0;
employees:
cout << "Eleven";
return 0;
}
基本上,我想将主菜单的主要部分转换成一个以某种方式持有goto短语的函数。我该怎么做呢?我的意思是,我明白goto和函数不能很好地协同工作,但还有另一种方法至少接近相同的工作吗?
答案 0 :(得分:4)
通常的方法是编写一个main_menu
函数来获取输入并返回一个指示所选内容的值:
enum choice { payroll, employees, quit };
choice main_menu() {
/* whatever */
return users_choice;
}
int main() {
bool done = false;
while (!done) {
switch(main_menu()) {
case payroll: do_payroll(); break;
case employees: do_employees(); break;
case quit: done = true; break;
}
}
return 0;
}
另外,要摆脱goto
函数中的login
(同样地,在菜单中),只需使用循环:
void login() {
string correctPass = "Love";
string attemptPass;
while (attemptPass != correctPass) {
/* whatever */
}
}
(我还将login()
的返回类型更改为void
,因为它当前没有返回有意义的值。)