I'm trying to write a program that generates a pseudorandom numbers using a seed. However, I'm running into problems.
I get this error
39 C:\Dev-Cpp\srand_prg.cpp void value not ignored as it ought to be
Using this code
#include <iostream>
#include <iomanip>
#include <sstream>
#include <limits>
#include <stdio.h>
using namespace std ;
int main(){
int rand_int;
string close ;
close == "y" ;
cout << endl << endl ;
cout << "\t ___________________________________" << endl ;
cout << "\t| |" << endl ;
cout << "\t| Pseudorandom Number Game! |" << endl ;
cout << "\t|___________________________________|" << endl ;
cout << endl << endl ;
while ( close != "y" ){
rand_int = srand(9);
cout << rand_int << endl ;
cout << " Do you wish to exit the program? [y/n] " ;
cin >> close ; }
}
srand() generates a seed (which is the number used to initialize the random number generator) and must be called once per process. rand() is the function you are looking for.
If you don't know what seed to pick, use the current time:
srand
doesn't return a random number, it just reseeds the random number generator. Callrand
afterwards to actually get a number:You're using
srand
incorrectly, that particular function is for setting the seed for later calls torand
.The basic idea is to call
srand
once with an indeterminate seed, then callrand
continuously to get a sequence of numbers. Something like:which should give you some random numbers between 0 and 9 inclusive.
You generally don't set the seed to a specific value unless you're testing or you want an identical sequence of numbers for some other reason. You also don't set the seed each time before you call
rand
since you're likely to get the same number repeatedly.So your particular
while
loop would be more like:srand returns void function and doesn't return a value.
Here you can see more about it. You'll just have to call srand(9) and get the value of rand() after that, like J-16 SDiZ pointed out, who will be upvoted for this :)
call it this way.