好吧,我正在准备考试,所以我试图让我的代码尽可能简单,但后来发生了一些非常奇怪的事情:练习是更改以下代码,并通过使用异常返回主菜单。
这是问题的代码:
void ha_ha_loop()
{
int i, c;
while(1)
{
for(i=0; i < 3; i++)
{
cout << "Ha Ha Ha" << endl;
sleep(3);
} // for
ask_return();
} // while
} // ha_ha_loop
void dollar_loop()
{
int i;
while(1)
{
for(i=0; i < 3; i++)
{
cout << "$$$$$$$$$ " << endl;
sleep(3);
} // for
ask_return();
} /* while */
} // dollar_loop
void mainloop()
{
string answer;
while (1)
{
cout << "Press 1 for Ha Ha Ha." << endl;
cout << "Press 2 for $$$$$$$$." << endl;
cout << "Press 3 for to quit." << endl;
cin >> answer;
switch (answer[0])
{
case '1':
ha_ha_loop();
case '2':
dollar_loop();
case '3':
return;
} // switch
} // while
} // mainloop
我所做的是:
void ask_return() {
char c;
cout << "Return to main menu? y/n:"<<endl;
cin >> c;
if (c=='y') throw 1;
}
void ha_ha_loop()
{
int i, c;
while(1)
{
for(i=0; i < 3; i++)
{
cout << "Ha Ha Ha" << endl;
} // for
ask_return();
} // while
} // ha_ha_loop
void dollar_loop()
{
int i;
while(1)
{
for(i=0; i < 3; i++)
{
cout << "$$$$$$$$$ " << endl;
} // for
ask_return();
} /* while */
} // dollar_loop
void mainloop()
{
char answer;
while (1)
{
cout << "Press 1 for Ha Ha Ha." << endl;
cout << "Press 2 for $$$$$$$$." << endl;
cout << "Press 3 for to quit." << endl;
cin >> answer;
switch (answer)
{
case '1':
ha_ha_loop();
case '2':
dollar_loop();
case '3':
return;
}
}
}
int main() {
try {
mainloop();
} catch (...) {
mainloop();
}
}
一开始它工作得很好,但有一次它用未处理的异常消息终止了我的程序。为什么?
最简单的正确方法是什么?
编辑:这是一种工作方式:
void ask_return() {
char c;
cout << "Return to main menu? y/n:"<<endl;
cin >> c;
if (c=='y') throw 1;
}
void ha_ha_loop()
{
int i, c;
while(1)
{
for(i=0; i < 3; i++)
{
cout << "Ha Ha Ha" << endl;
} // for
ask_return();
} // while
} // ha_ha_loop
void dollar_loop()
{
int i;
while(1)
{
for(i=0; i < 3; i++)
{
cout << "$$$$$$$$$ " << endl;
} // for
ask_return();
} /* while */
} // dollar_loop
void mainloop()
{
char answer;
while (1)
{
try {
cout << "Press 1 for Ha Ha Ha." << endl;
cout << "Press 2 for $$$$$$$$." << endl;
cout << "Press 3 for to quit." << endl;
cin >> answer;
switch (answer)
{
case '1':
ha_ha_loop();
case '2':
dollar_loop();
case '3':
return;
}
} catch (...) {
}
}
}
int main() {
mainloop();
}