Randomly printing out a string

Mar 25, 2017 at 6:54pm
Hello, in my code i need to print out a random Harry Potter spoiler out of 5 of them, this is what i have so far:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>
#include <string>

using namespace std;

int main ()
{
        string spoilers[5]={"Harry dies.", "Voldemort dies.", "Dumbledore    dies.", "Snape dies.", "Hermione and Ron get together."};

        cout << "This program outputs a random Harry Potter spoiler so be prepared!\n";

        return 0;
}

Mar 25, 2017 at 7:05pm
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <iostream>
#include <string>
#include <ctime>

using namespace std;

int main ()
{
    //number for array (better to use vector in most cases)
    const int arraySize = 5; //also used as maxNum in number generator
    string spoilers[arraySize]={"Harry dies.", "Voldemort dies.", "Dumbledore dies.", "Snape dies.", "Hermione and Ron get together."};
    
    cout << "This program outputs a random Harry Potter spoiler so be prepared!\n";
    
    //seed random number generator
    srand(time(NULL));
    
    //get a random number between 0-4 (elements in the array)
    int randomNum = rand() % arraySize + 0;
    
    cout << "The spoiler is...";
    //place randomNum into element of array to be selected at random
    cout << spoilers[randomNum] << endl;
    return 0;
}
Mar 25, 2017 at 7:32pm
thank you so much!! im not familiar with randomizing variables at all!
Mar 25, 2017 at 8:01pm
when i try to compile the code it says "main.cpp:14:23: error: ‘rand’ was not declared in this scope
int randomNum = rand() % arraySize + 0;"
how would i fix this?

Mar 25, 2017 at 8:18pm
What compiler are you using?

Try adding: #include <cstdlib>
Topic archived. No new replies allowed.