开发者

C++ Guess Number game crashing on other computers and infinite loop fix

// 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 thinkin开发者_StackOverflow社区g 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;
}

My code runs fine on my computer but when a friend of mine tries to run it, The program crashes. Does this have to do with my coding? Also I found that when I enter a letter for a guess, my game goes into an infinite loop. How can I go about fixing this issue?


The "crash" is probably related to missing runtime libraries, which would result in an error message similar to

The application failed to initialize properly [...]

...requiring your friend to install the missing runtime libraries, e.g.

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

Choose the version that matches whatever version of Visual Studio you used to develop your application, as well as the target platform.

As for your application entering an infinite loop: after entering a letter, the input stream will be in an error state and thus unusable. Code similar to the following will prevent that:

#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');

Basically, the code clears the error bits and removes any remaining input from the input buffer, leaving the stream in an usable state again.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜