When I start the program I always get a random number, that works fine. However when I guess the number and then say I want to play again, the number I am going to guess is the same as it was before. I tried putting there srand(time(0)); but that does not work for me. I am only a beginner in C++ so could someone tell me how can I fix it or what to do with it? Here is my code:
#include <iostream>
#include <string>
#include <random>
#include <time.h>
using namespace std;
int main()
{
srand(time(0));
int NumberToGuess = rand() % 1000;
string UserGuess;
int GuessCount = 0;
bool ContinuePlaying = true;
while (ContinuePlaying)
{
cout << "Guess a number between 0 and 999" << endl;
cin >> UserGuess;
GuessCount++;
int UserNumber = stoi(UserGuess);
if (UserNumber == NumberToGuess)
{
cout << "You guessed correctly. Congratulations you won the game." << endl;
cout << "It took you " << GuessCount << " guesses to guess the number." << endl;
cout << "Do you want to play again (y/n)?" << endl;
string playAgain;
cin >> playAgain;
if (playAgain == "y")
{
int NumberToGuess = rand() % 1000;
GuessCount = 0;
}
else if (playAgain == "n")
{
cout << "Thank you for playing" << endl;
ContinuePlaying = false;
}
else
{
cout << "Error: 505";
ContinuePlaying = false;
}
}
else if (UserNumber > NumberToGuess)
{
cout << "My number is lower, please try again." << endl;
}
else if (UserNumber < NumberToGuess)
{
cout << "My number is higher, please try again." << endl;
}
}
}
Aucun commentaire:
Enregistrer un commentaire