Random number and classes/functions [closed]

  c++

Can someone tell me why when I use this code by itself in the int main to make a random generator game the code works, but when I put the same code as a header & class it keeps randomizing the number. The random number isn’t suppose to change when the program is in the loop checking if the user’s input is equal to the generated number. For some reason the number keeps changing to a new random number after every check.

int main(){}
rndNumber Game;
Game.generate();
Game.guess();

return 0;

header.h

#pragma once
#include <iostream>
#include<stdlib.h>
#include<ctime>

using namespace std;

class rndNumber {
public:
rndNumber();
int generate();
void guess();
};

function cpp

    rndNumber::rndNumber() {
    cout << "Generating random number..."<<flush;

}

int rndNumber::generate() {
    srand(time(0));
    int x = rand() % 100 + 1;
    srand(x);
    //using this to check and make sure function works
    cout << x << endl;
    return x;
}

void rndNumber::guess() {
    cout << endl << "Guess the number..." << flush;
    int input = 0;
    while (input != generate()) {
        cin >> input;
        if (input == generate()) {
            cout << "You win!!!";
        }
        else if (input < generate()) {
            cout << "Your guess is too low try guessing higher...";
        }
        else if (input > generate()) {
            cout << "Your guess is too high try guessing lower...";
        }
    }
}

Source: Windows Questions C++

LEAVE A COMMENT