Original Post
I''m writing a little routine for a game of mine that generates random output in appropriate locations. I can get it to work the long way just fine, but I was wondering if there was another less redundant way. Here''s the long way.
void rand_gen(void)
{
string rnd_inv;
int rnd_num_inv;
string inv1 = "That wasn''t one of the options.?";
string inv2 = "Hey, nitwit, try choosing a VALID option!";
string inv3 = "You have to choose a listed option.";
rnd_num_inv = rand()%3;
if (rnd_num_inv == 0)
return inv1;
else if (rnd_num_inv == 1)
return inv2;
else if (rnd_num_inv == 2)
return inv3;
}
Now that might work fine, but I don''t feel like changing and adding all those freaking lines everytime I have to add just ONE more string. So, I''ve decided to try and come up with a better way using arrays. (This code is for the "Press any key" output, the other was for "Invalid Option" but it doesn''t matter...they do the same thing.)
#includeI think the setup is correct, but how do I figure out the number of elements in the array to put in place of "THIS_IS_THE_NO_OF_ELEMENTS_IN_ARRAY". I don''t want to declare string pak[] with a set number of elements because I want it to dynamically change every time I add another string. Therefore if I wanted another possible output string, I would only have to add it inside the { } and that would be IT! I wouldn''t have to change anything else. Get what I''m saying? --- Joker2000 Stevie Ray Vaughan - The Legend#include #include #include #include int main() { string rnd_pak; int rnd_num_pak; int i = 0; int count = 0; srand((unsigned)time(NULL)); string pak[] = {"Press a key to continue", "What are you waiting for?!", "You can stop wasting my time."}; for (i = 0; i < THIS_IS_THE_NO_OF_ELEMENTS_IN_ARRAY; i++) count++; rnd_num_pak = rand()%count; cout << endl << pak[rnd_num_pak]; }