Reputation: 27
#include <cstdlib>
#include <cmath>
#include <string>
#include <iostream>
#include <cstring>
#include <vector>
using namespace std;
int main()
{
int size = 0;
int test = 0;
string phrase, sentence;
test = rand() % 4 + 1;
cout << "#" << test << endl;
switch(test)
{
case 1:
phrase = "thing";
sentence = "computer science";
case 2:
phrase = "Subject";
sentence = "math and science";
case 3:
phrase = "Subject";
sentence = "pony and unicorn";
case 4:
phrase = "Subject";
sentence = "dinosaurs and rhino";
};
cout << "The phrase is..." << phrase << endl;
cout << "Here is your sentence..." << sentence << endl;
int length;
length = sentence.length();
char letter;
int arysize[length];
for(int z = 0; z < length; z++)
{
arysize[z] = 0;
}
int count = 0;
while(count != 10)
{
cout << "Enter a letter" << endl;
cin >> letter;
for(int j = 0;j < length; j++)
{
if(sentence[j] == letter)
{
arysize[j] = 1;
}
else if (sentence[j] == ' ')
arysize[j] = 1;
}
for (int m = 0; m < length; m++)
{
if(arysize[m] == 1)
{
cout << sentence[m];
}
else
cout << "_";
}
count++;
cout << "You have " << 10 - count << " tries left." << endl;
}
}
Sorry for this mess because I was creating a sample and was doing trial and error to get the outcome. When I use the rand() with 4 + 1, I should get a number between 1 -4. But whenever I run the program, I always get 4. How come it does not randomly select a number but instead, always giving me the same number?
THanks guys! Just to make sure that if anyone else is reading... you have to include the
#include <ctime>
header in order for it to seed.
Upvotes: 1
Views: 187
Reputation: 10378
Probably because you are not seeding it. Try using srand()
before your first rand()
call like this:
srand (time(NULL));
Upvotes: 4
Reputation: 7930
You need to seed the random number generator before you use it. Try inserting this line before you use rand()
the first time:
srand (time(NULL));
That will seed the random number generator with the current time, allowing for more random values.
This answer talks about why you need to seed the random number generator.
Upvotes: 3