Randomly selecting word from string array

Hey guys, I am trying to randomly select a word from my string list. I'm making a hangman game right now. I'm confused on where I should go from here.
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
  int getRandomGenerator()
{

	int value = 0;

	srand(static_cast<int>(time(0)));
	value = 1 + rand() % (10 - 1 + 1);





	return value;

}

int stringList()
{
	//Calling pre defined words 
	const int HANGMAN_WORDS = 10;
	
	string name [HANGMAN_WORDS] = { "apple", "orange", "car", "truck", "bicycle", "cat", "dog", "snake", "rock", "sock" };
	
	

	return 0;
}



I want the generator to randomly pick from the string list so it will be the word that the user has to guess for the game. I tried setting the string = to getRandomGenerator but I just end up getting an error.

Thanks.
closed account (48T7M4Gy)
If you generate a random number x say, then a randomly selected word would be name[x]. Make sure x is within the range of the name array. i.e. 0 <= x < 10 in your case
Last edited on
closed account (48T7M4Gy)
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
#include <stdlib.h>
#include <time.h>
#include <iostream>
#include <string>

using std::cout;
using std::endl;
using std::string;

int getMeARandomNumber(int);
string getMeAWord( int, string[]);

int main()
{
	string name[] = { "apple", "orange", "car", "truck", "bicycle", "cat", "dog", "snake", "rock", "sock" };
	int limit = sizeof(name)/sizeof(string);
	
	int x = getMeARandomNumber(limit);
	string word = getMeAWord(x, name);
	cout << x << ' ' << word << endl;
        
        return 0;
}

int getMeARandomNumber(int limit)
{
	srand(time(NULL));
	return rand() % limit;
}

string getMeAWord(int y, string wordList[])
{
	return wordList[y];
}


2 car
 
Exit code: 0 (normal program termination)
Last edited on
closed account (48T7M4Gy)
Or dispense with x altogether:

string word = getMeAWord( getMeARandomNumber(limit), name );
Last edited on
Topic archived. No new replies allowed.