Random Variable

I'm new to programming in C++ and I'm trying to figure out how to choose a random variable out of a selection of given variables. There were other posts I found on this topic but none of them quite clarified it for me.

This is my script:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
//Magic 8-ball.
#include <iostream>
using namespace std;

int main ()
{
    string answer[3]; //These are the 4 possible answers
    answer[0] = "Yes."; 
    answer[1] = "No.";
    answer[2] = "Maybe.";
    answer[3] = "Ask again later.";
    int r = rand()%4; //To roll which one of these will be said.
    int blank;
    cout << answer[r];
    cin >> blank; //Blank Cin line so the cmd doesn't close immediately.
    return 0;
}


It doesn't error message, but the program it creates doesn't respond when I run it and crashes. What am I doing wrong here?
The Wizard wrote:
string answer[3]; //These are the 4 possible answers

Notice anything strange there? ;-)

Also, unless you seed the PRNG you'll just get the same "random" string every time.
Last edited on
Oh, my bad. Thanks. I though if I put 3 it'd make 0, 1, 2, and 3.

It works now, but it only gets "No." as an answer. What should I do about that?
Last edited on
When you're declaring arrays, you declare the size you want. The index will always start at zero and contain the number of elements you've specified.

So, your original array would have only contain 0, 1 and 2 as you specified a size of three. When you were trying to access a fourth element, with an index of 3 (your "Ask again later" line), you were trying to access an out of bounds array index.

Like I said, you need to seed the random number generator. You can pass a number into it but the best convention is to use the system time as a seed.
Here's a quick example:
1
2
3
4
5
6
7
8
9
10
#include <iostream>
#include <ctime>

int main( int argc, char* argv[] )
{
   srand( time( NULL ) );  // Seed PRNG

   // Output random number between 1 and 10
   std::cout << rand() % 10 + 1;
}

It works now. Thanks.
Topic archived. No new replies allowed.