2015-05-23 28 views
0

我目前正在編寫遊戲「Mastermind」的一個版本,並且希望在用戶輸入字母'Q'時不管它是從主菜單還是從主菜單中退出在比賽期間被要求做出猜測。用C++函數中的用戶輸入退出程序

我遇到的問題是,選定的用戶輸入是從一個函數內進行評估的,通常從另一個函數中調用,我不確定如何正確退出遊戲而不忽略當前堆棧的清理。我想我可以嘗試做一個自定義的異常(雖然我不確定如何在C++中做到這一點,仍然在學習),然後將每個調用放在main()中,稍後可以調用menuSelection()函數。嘗試抓住,但我不知道這是否是最佳的。

我會嘗試給出一個我的程序的快速非常概括的例子。很明顯,它只是爲了顯示我的程序在什麼時候遇到退出場景。

void printMainMenu(){ 
    cout<<"blah blah blah... Enter a selection: "; 
    string input; 
    getline(cin, input); 
    menuSelection(input); 
} 

void menuSelection(string input){ 
    if(input == 'Q') 
     Exit Program; // <-- Need to exit when here 
    else 
     (other options); 
} 


int main(){ 
    printMainMenu(); // <-- menuSelection called here 

    while(cin >> solution){ 
     GameBoard currentGame = GameBoard::GameBoard(solution); 
     cout>>"Please make a guess or enter 'Q' to quit: "; 
     string guess; 
     getline(cin, guess); 

     if(guess.size() == 1) 
      menuSelection(guess); // <-- and here 
     else 
      currentGame.checkGuess(guess); 
    } 
} 

會放置每個menuSelection或printMenu中的呼叫嘗試捕捉是處理這個最有效的方法是什麼?

+1

爲什麼不直接叫'出口(0)'? – Christophe

+1

exit(0)我相信不會展開堆棧,只會調用當前在範圍內的變量的析構函數。因此,將所有其他物體留下不明。這可能是不正確的,因爲我說我對C++相當陌生,但這是我的理解。 –

回答

0

最簡單的辦法是要麼退出(0)(我不推薦,因爲它沒有展開堆棧)或投擲它在程序的頂級捕獲的異常。

編輯:代碼

void menuSelection(string input){ 
    if(input == 'Q') 
     throw std::runtime_error; // Maybe use another exception class 

主要功能將成爲

int main(){ 
    printMainMenu(); // <-- menuSelection called here 

    try { 
     while(cin >> solution){ 
      GameBoard currentGame = GameBoard::GameBoard(solution); 
      cout>>"Please make a guess or enter 'Q' to quit: "; 
      string guess; 
      getline(cin, guess); 

      if(guess.size() == 1) 
       menuSelection(guess); // <-- and here 
      else 
       currentGame.checkGuess(guess); 
     } 
    } 
    catch (const std::exception& e) 
    { 
     // Quit 
    } 
} 
0

我會這樣做的方式是有一個班級管理整個遊戲。如果它應該退出,這將有一個bool sigalling。所有這些職能都將成爲這個班級的成員。

class GameLogic { 
    bool should_quit = false; 

    void mainLoop() { 
    while (!should_quit) { 
     // call whatever you need 
    } 
    } 
    void someDeepNestedCalledFunction() { 
    if (whatever_reason) { 
     should_quit = true;  
     return; 
    } 
    } 
}; 
相關問題