Still learning :)

Okay,

So I have a class called songs. I have about 4 songs that i would like to randomly pick one of the 4 songs. I was working on a small program to try and accomplish this but no luck.

Anyone have some insight they may be able to offer.

Thanks
V
First things first, you should name your topics something more specific.

Also, if you could post some/all of the code from the program you wrote it would be easier to critique your work.
Put the songs in an array, then access a random element:

1
2
3
4
5
6
Song **songs = new Song*[4];
for(int i = 0; i < 4; ++i)
   songs[i] = new Song;

Song *selectedSong = songs[ rand() % 4 ];
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

#include <vector>
#include <cstdlib>
#include <time>
using namespace std;
vector<song*> Songs;  //vector storage is good for random access

int numSongs = 0;
int randomSongIndex = 0;

//add songs, increment the number of songs 

srand(time());
randomSongIndex = rand() % numSongs + 1;

Songs[randomSongIndex]->Play();
Last edited on
Topic archived. No new replies allowed.