さて、私は試験勉強をしているので、コードをできるだけシンプルにしようとしましたが、非常に奇妙なことが起こりました。次のコードを変更し、例外を使用してメインメニューに戻るという演習でした。
質問のコードは次のとおりです。
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();
}