2011-06-01 26 views
1
// Guess my number 
// My first text based game 
// Created by USDlades 
// http://www.USDgamedev.zxq.net 

#include <cstdlib> 
#include <ctime> 
#include <string> 
#include <iostream> 

using namespace std; 


int main() 
{ 

    srand(static_cast<unsigned int>(time(0))); // seed the random number generator 

    int guess; 
    int secret = rand() % 100 + 1; // Generates a Random number between 1 and 100 
    int tries =0; 

    cout << "I am thinking of a number between 1 and 100, Can you figure it out?\n"; 

    do 
    { 
     cout << "Enter a number between 1 and 100: "; 
     cin >> guess; 
     cout << endl; 
     tries++; 

     if (guess > secret) 
     { 
      cout << "Too High!\n\n "; 
     } 
     else if (guess < secret) 
     { 
      cout << "Too Low!\n\n "; 
     } 
     else 
     { 
      cout << "Congrats! you figured out the magic number in " << 
        tries << " tries!\n"; 
     } 
    } while (guess != secret); 

    cin.ignore(); 
    cin.get(); 

    return 0; 
} 

我的代碼在我的電腦上運行良好,但是當我的一個朋友試圖運行它,程序崩潰。這是否與我的編碼有關?我還發現,當我輸入一個猜測信時,我的遊戲進入無限循環。我該如何解決這個問題?C++猜數遊戲崩潰在其他計算機和無限循環修復

+1

所以... *它怎麼會崩潰?在什麼操作系統上?用什麼輸入? – 2011-06-01 03:26:30

+0

當她在Windows Vista Premium上打開它時,它崩潰,甚至沒有加載我的遊戲我不認爲 – USDblades 2011-06-01 03:27:42

+0

它在崩潰時顯示在屏幕上的消息是什麼? (如果你還不知道,*找出*,這可能會直接導致解決您的問題。) – 2011-06-01 03:28:40

回答

5

的「撞車」,可能與缺少的運行時庫,這將導致類似於

應用程序的錯誤消息未能正確[...]

初始化 。 ..要求你的朋友安裝缺少的運行時庫,例如

http://www.microsoft.com/downloads/en/details.aspx?familyid=a5c84275-3b97-4ab7-a40d-3802b2af5fc2&displaylang=en

http://www.microsoft.com/downloads/en/details.aspx?FamilyID=a7b7a05e-6de6-4d3a-a423-37bf0912db84

選擇一個Visual Studio中您用來開發應用程序,以及作爲目標平臺的任何版本相匹配的版本。

至於你的應用程序進入無限循環:輸入一個字母后,輸入流將處於錯誤狀態,因此不可用。類似於以下代碼將防止:

#include <limits> 
... 
... 
... 
std::cout << "Enter a number between 1 and 100: "; 
std::cin >> guess; 
std::cin.clear(); 
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); 

基本上,代碼clears錯誤比特和removes任何剩餘的輸入從輸入緩衝器,在一個可用狀態再次離開流。

+0

我試過你的代碼,它將字母當作猜測而不是進入無限循環。謝謝你,吉姆。 – USDblades 2011-06-01 03:49:06