2016-05-28 149 views
-2

遇到我的代碼無法正常工作的問題。我試圖通過按下鍵盤上的任意鍵,但不按回車鍵來退出該操作。我的代碼片段如下。按下任意鍵而不按下回車鍵退出「do while」?

void LemonadeBuyANDCheck() 
{ 
    int iCupsToBuy = rand() % (MAX_CUPS - MIN_CUPS) + MIN_CUPS; 


    bool continueLoop = true; 
    do 
    { 
     int Userinput = 1; 
     Userinput = !_kbhit(); 
     fflush(stdin); 

     if (Userinput == 1) 
     { 
      continueLoop = false; 
     } 

     StoreIsOpen(); 
     int randomNumber = rand() % 100; 

     if (iCupsOfLemonadeInStock == 0) 
     { 
      cout << "Customer came to buy some lemonade but you didnt have any in stock :(\n"; 
      //continueLoop = false; 
     } 

     else if (randomNumber <= 25) 
     { 

      cout << "Wow your lemonade is way too expensive!\n"; 
      iCustomerCounter++; 

     } 

     else if (randomNumber >= 75) 
     { 

      cout << "Eww your recipe for lemonade... Wow..\n"; 
      iCustomerCounter++; 
     } 


     else if (iCupsOfLemonadeInStock >= iCupsToBuy) 
     { 

      cout << "You sold " << iCupsToBuy << "cups of lemonade!\n"; 

      iCupsOfLemonadeInStock = iCupsOfLemonadeInStock - iCupsToBuy; 
      iCupsOfLemonadeSold = iCupsOfLemonadeSold - iCupsToBuy; 
      //Money 

      fMoneyEarned += (iCupsToBuy * fCurrentLemonadePrice); 
      fCurrentMoney += (iCupsToBuy * fCurrentLemonadePrice); 

      iCustomerCounter++; 
     } 
     else if (iCupsOfLemonadeInStock < iCupsToBuy) 
     { 
      cout << "You didnt have enough lemonade in stock so you only sold " << iCupsToBuy - iCupsOfLemonadeInStock << endl; 

      fMoneyEarned += (iCupsOfLemonadeInStock * fCurrentLemonadePrice); 
      fCurrentMoney += (iCupsOfLemonadeInStock * fCurrentLemonadePrice); 
      iCupsOfLemonadeInStock = 0; 

      iCustomerCounter++; 
     } 
    } while (continueLoop != true); 
    fflush(stdin); 
     GameMenuSelectionVerifier(); 
} 
+0

你試過尋找答案嗎?先打:http://stackoverflow.com/questions/7010760/c-keypress-getch-cin-get – Jens

+0

你有什麼問題? – user463035818

+1

C++標準庫不提供「check for keypress」功能,但您可以使用庫如ncurses。 –

回答

0

我想你可以使用名爲「kbhit」的函數,它位於「conio.h」頭文件中。詳情請點擊this。你可以這樣修改:

while(!kbhit()); 
+0

我們在哪裏可以得到這個「conio.h」頭文件?如果我們想要編寫一個應用程序,而又不清除我們的舊16位MS-DOS計算機,該怎麼辦? –

+0

「conio.h」頭文件很常見,就像「stdio.h」頭文件一樣。你只需要寫「#include 」,電腦就能找到它。然後你可以使用kbhit函數。 – fgksgf

+0

常見?哈! 20多年來這種情況並不常見。我可以借用你的時間機器嗎? –