Jump to content

Noob C++ loops help

KushKomputers
Go to solution Solved by MikeD,


#include <iostream>

#include <string>

#include <cstdlib>

#include <ctime>

using namespace std;

int main() {

int yourGuess, randomNumber;

string playAgain;

srand(time(NULL));

cout << "Let's play a game. I will come up with a number and you will have to guess it." << endl;

do {

randomNumber = (rand() % 20) + 1;

do {

cout << "Guess a number: ";

cin >> yourGuess;

if(yourGuess > randomNumber)

cout << "Nope! You were too high." << endl;

else if(yourGuess < randomNumber)

cout << "Nope! You were too low." << endl;

} while(yourGuess != randomNumber);

cout << "Winner Winner!!! You got my number!" << endl;

cout << "Play again?[y/n]: ";

cin >> playAgain;

} while(playAgain == "y");

return 0;

}

Hey guys, I just began taking a class for programming at my school based around c++ using codebocks. One of my assignments was to create a random number guessing game. I made the program and it works but i wanted to give the user a option to play the game again. I was thinking about putting the whole thing in another do while loop bit i don't know how to do it without the program asking the user if they wanted to play again the first time they played. 

 

this is what i have so far

 

#include <iostream>#include <cstdlib>#include <ctime>#include <string> using namespace std; int main(){        srand(time(0));        int yourGuess;        int  randomNumber = (rand() % 20)+1;        cout << "Let's play a game. I will come up with a number and you will have to guess it.\n";          do        {            cout <<"Guess a number: ";            cin >> yourGuess;             if(yourGuess == randomNumber)            {                cout << "Winner Winner!!! You got my number!" << endl;            }             if(yourGuess > randomNumber)            {                cout << "Nope! You were too high." << endl;            }             if(yourGuess < randomNumber)            {                cout << "Nope! You were too low." << endl;             }        }        while(yourGuess != randomNumber);    return 0;}
Edited by alpenwasser
added code tags

AMD FX-8350 OC to 4.5ghz      Evga gtx 660       SilverStone FT03      Samsung 840 128gb  

Link to comment
Share on other sites

Link to post
Share on other sites

With my limited knowledge, should it not be else if else if for the subsequent if statements past the first if statement?

 

Could you do a while loop where you just exit the program to stop it?

Link to comment
Share on other sites

Link to post
Share on other sites

Could you put that all into a function and then run the function at the start of the program? If you do that, at the end you can have an if statement asking if they want to play again. If they want to play again you can run the function over and if they don't then close it down.

Setup: i5 4670k @ 4.2 Ghz, Corsair H100i Cooler, Corsair Vengeance Pro 16GB Ram @ 1600 Mhz, MSI Z87-GD65 Motherboard, Corsair GS700 2013 edition PSU, MSI GTX 770 Lightning, Samsung EVO 120 SSD + 2TB&1TB Seagate Barracudas, BenQ XL2411T Monitor, Sennheiser HD 598 Headphones + AntLion ModMic 4.0

Link to comment
Share on other sites

Link to post
Share on other sites

Add another do while loop and ask if they want want to play again after the game loop.

1474412270.2748842

Link to comment
Share on other sites

Link to post
Share on other sites

What I would do actually is put the whole thing inside a while loop with a boolean like Play = Yes set by default when it's defined, and the loop/program repeats as long as Play == Yes.  Then in the winning if-statement, add a cin asking if they want to play again after the You Win message.  If yes || Yes, continue;  If != yes && != Yes, return 0;

Link to comment
Share on other sites

Link to post
Share on other sites

idea:

 char ans = 'Y'; do        {            cout <<"Guess a number: ";            cin >> yourGuess;             if(yourGuess == randomNumber)            {                cout << "Winner Winner!!! You got my number!" << endl;                cout << "Want to play again? Y/N" << endl;                cin >> ans;            }             else if(yourGuess > randomNumber)            {                cout << "Nope! You were too high." << endl;            }             else            {                cout << "Nope! You were too low." << endl;             }        }        while(yourGuess != randomNumber && ans == 'Y');    return 0;}
Edited by alpenwasser
code tags :)

CPU: Intel i7 3970X @ 4.7 GHz  (custom loop)   RAM: Kingston 1866 MHz 32GB DDR3   GPU(s): 2x Gigabyte R9 290OC (custom loop)   Motherboard: Asus P9X79   

Case: Fractal Design R3    Cooling loop:  360 mm + 480 mm + 1080 mm,  tripple 5D Vario pump   Storage: 500 GB + 240 GB + 120 GB SSD,  Seagate 4 TB HDD

PSU: Corsair AX860i   Display(s): Asus PB278Q,  Asus VE247H   Input: QPad 5K,  Logitech G710+    Sound: uDAC3 + Philips Fidelio x2

HWBot: http://hwbot.org/user/tame/

Link to comment
Share on other sites

Link to post
Share on other sites

Another option would be to simply put it into a while(true) loop, which will keep looping infinitely for as long as you're entering a guess. You can add in an extra conditional to check for an exit command.

 

Something like:

"Enter a number (or type exit to stop playing):"

 

If the user enters "exit", you'd use a break; statement to break out of the infinite loop. 

Interested in Linux, SteamOS and Open-source applications? Go here

Gaming Rig - CPU: i5 3570k @ Stock | GPU: EVGA Geforce 560Ti 448 Core Classified Ultra | RAM: Mushkin Enhanced Blackline 8GB DDR3 1600 | SSD: Crucial M4 128GB | HDD: 3TB Seagate Barracuda, 1TB WD Caviar Black, 1TB Seagate Barracuda | Case: Antec Lanboy Air | KB: Corsair Vengeance K70 Cherry MX Blue | Mouse: Corsair Vengeance M95 | Headset: Steelseries Siberia V2

 

 

Link to comment
Share on other sites

Link to post
Share on other sites

Another option would be to simply put it into a while(true) loop, which will keep looping infinitely for as long as you're entering a guess. You can add in an extra conditional to check for an exit command.

Something like:

"Enter a number (or type exit to stop playing):"

If the user enters "exit", you'd use a break; statement to break out of the infinite loop.

"if the user enters 'exit'" should be the condition to exit the loop, instead of using a wild while(true) in conjunction with a not-sexy if-break

Link to comment
Share on other sites

Link to post
Share on other sites

idea:

char ans = 'Y';

do

{

cout <<"Guess a number: ";

cin >> yourGuess;

if(yourGuess == randomNumber)

{

cout << "Winner Winner!!! You got my number!" << endl;

cout << "Want to play again? Y/N" << endl;

cin >> ans;

}

else if(yourGuess > randomNumber)

{

cout << "Nope! You were too high." << endl;

}

else

{

cout << "Nope! You were too low." << endl;

}

}

while(yourGuess != randomNumber && ans == 'Y');

return 0;

}

I tried this but the "random number" was the same every time I ran it

AMD FX-8350 OC to 4.5ghz      Evga gtx 660       SilverStone FT03      Samsung 840 128gb  

Link to comment
Share on other sites

Link to post
Share on other sites

I tried this but the "random number" was the same every time I ran it

you need to call srand to get different "random" numbers every time
Link to comment
Share on other sites

Link to post
Share on other sites

you need to call srand to get different "random" numbers every time

He's just not calling rand again for the next game.

1474412270.2748842

Link to comment
Share on other sites

Link to post
Share on other sites

He's just not calling rand again for the next game.

oh my bad, i misinterpreted the post and only read the last snippet of code
Link to comment
Share on other sites

Link to post
Share on other sites

It's because the computer never picks another number. It generates one number and then loops the guessing portion over and over.  "Playing again" only keeps looping the guessing portion.  You need to have at least two nested loops, one for retrying failed guesses within a round, and an outer loop that includes the random number generator in it for making a new round.

Link to comment
Share on other sites

Link to post
Share on other sites

You could just add generation in case the answer was 'Y':

if(yourGuess == randomNumber)            {                cout << "Winner Winner!!! You got my number!" << endl;                cout << "Want to play again? Y/N" << endl;                cin >> ans;                                if(ans == 'Y')                   {                       randomNumber = generate_new_number();                   }            }

CPU: Intel i7 3970X @ 4.7 GHz  (custom loop)   RAM: Kingston 1866 MHz 32GB DDR3   GPU(s): 2x Gigabyte R9 290OC (custom loop)   Motherboard: Asus P9X79   

Case: Fractal Design R3    Cooling loop:  360 mm + 480 mm + 1080 mm,  tripple 5D Vario pump   Storage: 500 GB + 240 GB + 120 GB SSD,  Seagate 4 TB HDD

PSU: Corsair AX860i   Display(s): Asus PB278Q,  Asus VE247H   Input: QPad 5K,  Logitech G710+    Sound: uDAC3 + Philips Fidelio x2

HWBot: http://hwbot.org/user/tame/

Link to comment
Share on other sites

Link to post
Share on other sites


#include <iostream>

#include <string>

#include <cstdlib>

#include <ctime>

using namespace std;

int main() {

int yourGuess, randomNumber;

string playAgain;

srand(time(NULL));

cout << "Let's play a game. I will come up with a number and you will have to guess it." << endl;

do {

randomNumber = (rand() % 20) + 1;

do {

cout << "Guess a number: ";

cin >> yourGuess;

if(yourGuess > randomNumber)

cout << "Nope! You were too high." << endl;

else if(yourGuess < randomNumber)

cout << "Nope! You were too low." << endl;

} while(yourGuess != randomNumber);

cout << "Winner Winner!!! You got my number!" << endl;

cout << "Play again?[y/n]: ";

cin >> playAgain;

} while(playAgain == "y");

return 0;

}

Link to comment
Share on other sites

Link to post
Share on other sites

#include <iostream>#include <string>#include <cstdlib>#include <ctime>using namespace std;int main() {  int yourGuess, randomNumber;  string playAgain;  srand(time(NULL));  cout << "Let's play a game. I will come up with a number and you will have to guess it." << endl;  do {    randomNumber = (rand() % 20) + 1;    do {      cout << "Guess a number: ";      cin >> yourGuess;      if(yourGuess > randomNumber)        cout << "Nope! You were too high." << endl;      else if(yourGuess < randomNumber)        cout << "Nope! You were too low." << endl;    } while(yourGuess != randomNumber);    cout << "Winner Winner!!! You got my number!" << endl;    cout << "Play again?[y/n]: ";    cin >> playAgain;     } while(playAgain == "y");  return 0;}

This works! thanks. I was wondering as to what the NULL inside "srand(time(NULL));" is doing for the program.

AMD FX-8350 OC to 4.5ghz      Evga gtx 660       SilverStone FT03      Samsung 840 128gb  

Link to comment
Share on other sites

Link to post
Share on other sites

This works! thanks. I was wondering as to what the NULL inside "srand(time(NULL));" is doing for the program.

The time function expects a pointer to a time_t struct where it would store the returned value. I prefer NULL to zero because, even though 0 is null, it's clearer.

Link to comment
Share on other sites

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×