Confused

Hi all

I'm really struggling to wrap my head around this. I am going through the word jumble game and this section is causing me a lot of problems

enum fields {WORD, HINT, NUM_FIELDS};
const int NUM_WORDS = 5;
const string WORDS[NUM_WORDS][NUM_FIELDS] =
{
{"wall", "Do you feel like banging your head against something?"},
{"glasses", "These might help you see the answer" },
{"labored", "Going slowly, is it?" },
{"persistant", "keep at it"},
{"jumble", "It's what the game is all about!",}
};

srand(time(0));

int choice = (rand() % NUM_WORDS);
string theWord = WORDS[choice][WORD]; //word to guess
string theHint = WORDS[choice][HINT]; //hint


Personally, i don't like the way this has been done, could it be reasonably be done this way instead? It makes more sense in my head

enum fields {WORD, HINT};
const int NUM_WORDS = 5;
const int NUM_HINTS = 5;
const string WORDS[NUM_WORDS][NUM_HINTS] =
{
{"wall", "Do you feel like banging your head against something?"},
{"glasses", "These might help you see the answer" },
{"labored", "Going slowly, is it?" },
{"persistant", "keep at it"},
{"jumble", "It's what the game is all about!",}
};







NUM_HINTS makes no sense since it must always be the same as NUM_WORDS. And it certainly wouldn't be the second dimension of WORDS, which must of course be 2 (i.e., NUM_FIELDS in the first code): one element for the word and one for the hint.

But the code is badly written. You should find better code to study. You should make a struct for the word and hint, and use a vector instead of a c-style array.

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 <vector>
using namespace std;

struct Word {
    string word;
    string hint;
};

const vector<Word> words {
    { "one",   "alpha" },
    { "two",   "beta"  },
    { "three", "gamma" }
};

int main() {
    for (const auto& w: words)
        std::cout << w.word << ": " << w.hint << '\n';
}


Thanks, i appreciate the feedback, it's from the book 'beginning c++ through game programming', i'm not up to structs yet but had a feeling the book wasn't the best which is why I've purchased 'Programming principles and practice' but still in the early stages of that book.

so, just so i understand correctly

enum fields {WORD, HINT, NUM_FIELDS}; (This just means 2)

const int NUM_WORDS = 5; (This just means 5)

const string WORDS[NUM_WORDS][NUM_FIELDS] = (This means create an array of 2 x 5)

My final question, how does it know to store the words in 'WORD' and the hints in 'HINT'?
For the enum, the WORD, HINT, and NUM_FIELDS tags are automatically assigned values starting at 0. So WORD is 0, HINT is 1, and NUM_FIELDS is 2.

Yes, the WORDS array is a 5 x 2 array.

You would access the i'th element's "word field" by saying WORDS[i][WORD] and the hint field by saying WORDS[i][HINT].
Last edited on
Ok, thank you again for your help, it's much appreciated
Topic archived. No new replies allowed.