Select a random word from an array and place it into a variable.

Hey guys I am doing Hangman C++ and I need to select a random word my array:

char *words[30]={"bad","easy","lol","Hurt","gay","code","hate","kill","ice","fire","icecream","hangman","destroy","computer","book","dictionary","technology","power","thunder","controller","dexterity","keyboard","thunderous","blizzard","hazardous","algorithm","destruction","operation","assignment","despicable"};

And place it into the variable:

secretword

I know this includes the random function, and I can get a random word to be selected and displayed on the screen but I need it to be selected and put into the variable for the purpose of hangman!
I can get a random word to be selected and displayed on the screen

What's the code you use for this?

Also, what's the type of your secretword variable?
Last edited on
secretword is a char at the moment. And the code I use is something along of the lines of:

1
2
3
srand ( time(NULL) );
cout << rand() % 30 ;


something along those lines, I had gotten rid of it for:

1
2
3
4
srand(time(NULL));
   random = rand() % 10;
   strcpy(&secretword[0],&words[random][0]);
   len =strlen(&secretword[0]);


But I get the error "Expression must have pointer to object type"
secretword should not be a char but an array of char of sufficient size, like
char secretword[30];
Last edited on
Or better, use std::strings.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
#include <string>
#include <cstdlib>
#include <ctime>

using namespace std;

int main()
{
    srand(time(0));

    const string wordList[4] = { "icecream",
        "computer", "dictionary", "algorithm" };

    string word = wordList[rand() % 4];

    cout << word << endl;

    return 0;
}
Thanks :)

What is a const by the way? Is a Const String a "Cstring" for short?
const means it can never be changed after it is first created.
const means it can never be changed after it is first created

Indeed.

const is short for constant and one of its uses is to define, well, constants. In the code above, wordList is an array of string constants. This means that, after they are initialized, you can't change their values.

std::strings like the ones in the code above are C++ style strings. A C style string, commonly called a C-string, is a sequence of characters terminated by the null character ('\0'). Unless you really have to, it's not a good idea to work with C-strings, as std::strings are easier to use.

EDIT: Unless you're talking about microsoft's CString, which is a class (user defined type) similar to std::string.
Last edited on
Topic archived. No new replies allowed.