C++ Tutorial #13 — Simple game with loops (sentinel loop, while / nested if else)


Topics Discussed: Making a simple number guessing game

Source Code Available Here
Source Code using srand for pseudorandomity

4 comments

  1. Beau says:

    #include
    #include
    using namespace std;

    int main(){
    cout << "Welcome to my guessing game! " << endl;
    cout << "Your goal to to guess the number the computer picked!" << endl;
    cout << "Good luck!" << endl;
    cout << "The computer numer is 1 – 1000 just to let you know. =)" << endl;
    int guess, compNum = rand()%1000;
    char quit;
    while (quit != 'y'){
    cout << "Please pick a number: " <> guess;

    while(guess!= compNum){

    if(guess < compNum){
    cout << "Your guess is less then what the computer picked! " << endl;
    cout << "Please try again: " <> guess;
    }
    else if (guess > compNum){
    cout <<"Your guess is greater then what the computer picked! " << endl;
    cout << "Please try again: " <> guess;
    }
    else {
    break;
    }
    }
    cout << "Congratulations! You guessed the right number!" << endl << endl;
    cout << "Would you like to quit now? y/n?" <> quit;
    }

    return 0;
    }

    for some reason this keeps on becoming a infinite loop, just was wondering why?? Sometimes it works and other times it just keeps repeating the loop very quickly.. and the rand()%1000 seems to always show up as 933 :S is there a way to make it a different number everytime you run the program?

    • Damien says:

      It comes out that way because of how you’re handling your input, if you’re taking in a char you should be using cin >> with a clear() or something like that to clear the “enter” that might still be in the buffer.

      Aside from that, to make your rand truly rand you need to do this:

      srand ( time(NULL) ); Then use rand, as that will seed it based on the time you call your program.

      If you have more questions don’t hesitate to ask, also, sorry about the very slow reply, I have been fairly inactive due to work / wrapping up school.

  2. Beau says:

    include iostream and cstdlib

  3. Beau says:

    Okay so I tried to run the program through the external program and it seems to be working just fine. (seems netbeans was being funky…) I still get it as 933 all the time so I was just wondering what is the way to make it more random?

Leave a Reply

Your email address will not be published. Required fields are marked *

*