Creating a message with each value

Mar 16, 2013 at 10:42pm
I created a program to generate 3 random numbers, but I can't figure out to get a message to go with them. Being as they're random, do I set a message for 1,2, and 3 as an int? If they weren't random it may be easier.

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
26
27
28
29
30
31
32
33
34
35
#include<iostream>
#define MAX_NUM 4

using namespace std;

void randnum()

{

int random;

srand(time(NULL));

for(int i=1;i<4;i++)

{

random=rand()%MAX_NUM;

cout<<random<<endl;
{

int main()

{


randnum();

system ("PAUSE");
return 0;

}

Mar 16, 2013 at 11:39pm
I'm not sure exactly what you're asking. Do you want to display the same message next to each number, or do you want the message to change depending on what the number is?
Mar 17, 2013 at 11:10am
I assume that each number will correspond with a specific message. One way is to use multiple if-else conditions, or a switch-case, but my preferred solution is to use a lookup table, in this case an array containing the different messages. Since the value of random may vary between 0 and 3, there are four possible messages.

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
26
27
28
29
30
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <string>

const int MAX_NUM = 4;

using namespace std;

void randnum()
{
    srand(time(NULL));
    
    string message[MAX_NUM] = 
        { "Apple", "Orange", "Banana", "Grapefruit" };

    for (int i=0; i<3; i++)
    {
        int random = rand() % MAX_NUM;
        cout << random << " " << message[random] << endl;
    }
}

int main()
{
    randnum();
    
    cin.get();
    return 0;
}


Notice the use of a constant rather than #define, this is the preferred method in C++.
Last edited on Mar 17, 2013 at 11:11am
Mar 17, 2013 at 6:25pm
Okay, thank you. I really appreciate the replies. You were correct about me needing a specific value for each random number, which really confused me when my professor gave me the assignment. After looking over you gave us it seems kind of easy to understand.
Topic archived. No new replies allowed.