guess the random number-some problem

Hello everbody! I tried to write a code to generate a random number that the user will then guess. My problem is, I alweys get 42, and i don't know why..can someone tell me what I got wrong?
here is my code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
#include <cstdlib>
using namespace std;
int main ()
{
    int magic, guess;
    magic=rand()%100+1;
    do {
        cout<<"Enter your Guess ";
        cin>> guess;
        if(guess==magic){
            cout<<"**RIGHT**"<<magic<<" is the number!\n";
        }
        else{
            cout<<"Sorry...you are wrong\n";
            if(guess>magic)
                cout<<"Your guess is too high\n";
                else cout<<"Your guess is too low\n";

        }
    }while(guess!= magic);
    return 0;
}

> My problem is, I alweys get 42, and i don't know why

The C random number generator is pre-seeded with a default value of 1. To get different sequences, we need to reseed it with different values.
http://www.cplusplus.com/reference/cstdlib/srand/

C++11:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
#include <random> // ***
#include <ctime>

int main()
{
    // create the pseudo random number generator seeded with a somewhat random value
    std::mt19937 rng( std::time(nullptr) ) ;
    rng.discard( std::mt19937::state_size ) ; // let it warm up

    // create a random number distribution
    std::uniform_int_distribution<int> distrib( 1, 100 ) ; // integers uniformly distributed in [1,100]

    // generate and print out a few pseudo random numbers evenly distributed in [1,100]
    for( int i = 0 ; i < 20 ; ++i ) std::cout << distrib(rng) << ' ' ;
    std::cout << '\n' ;
}

http://coliru.stacked-crooked.com/a/c45787a3a3b7e75d
http://rextester.com/LQMZG15577
Topic archived. No new replies allowed.