0

I am trying to find a way to randomly choose a word from a 2d char array and put it in another char array. Here is my code:

    char wordbank[5][20] = {"house", "car", "tree", "bicycle", "shark"};
    int random = rand() % 5;
    char word[20] = wordbank[random];

I am getting a compiler error on the last line that says: Array must be initialized with brace a enclosed initializer. what would be the proper way of doing this?

7
  • 4
    If you are working with strings, use std::string in C++. Also, make sure to specify exact error messages. We can't see your computer screen. Commented Aug 28, 2015 at 12:51
  • rand() % 0. . ?? Division by Zero .! ! ! Even if you compile successfully it should crash.! Commented Aug 28, 2015 at 13:06
  • 1
    you have a conflict between wordbank and wordbook - I assume they should be the same... Commented Aug 28, 2015 at 13:10
  • @StillLearning: That's the actual answer, which will solve the compiler error that OP is asking about. The logic error with modulo 0 will certainly throw a wrench in things, though. Commented Aug 28, 2015 at 13:22
  • the wordbank and wordbook problem was just because of spellcheck when i was typing the question. I tried to improve the question a bit so hopeful its more clear now Commented Aug 28, 2015 at 13:38

6 Answers 6

1

You are getting a compile error because you trying to assign a char* to an array of chars.

Since wordbank is a 2D array wordbank[index] will be a char* (pointer to char). C and C++ has no implicit conversion from char* to array of char. Consequently you'll get a compile error.

If you want a copy of a random string in wordbank, it can be done like this:

char wordbank[5][20] = {"house", "car", "tree", "bicycle", "shark"};
srand (time(NULL));
int random = rand() % 5;
char word[20];
strcpy(word, wordbank[random]); // strcpy (string copy) takes a copy of the 2nd string
                                // (i.e. wordbank[random]) and puts it into the 1st 
                                // string (i.e. word).

If you just want to point to a random string in wordbank, it ca be done like this:

char wordbank[5][20] = {"house", "car", "tree", "bicycle", "shark"};
srand (time(NULL));
int random = rand() % 5;
char* word = wordbank[random]; // word is a pointer to a string. It is
                               // initialized to point to the string
                               // held by wordbank[random]

With the first method you can change the value of word without changing the value of wordbank. With the second method you will change both at the same time.

BTW - use std::string instead of C-style string and vector instead of array. If you really want an array the use the C++ style instead.

Something like:

vector<string> wordbank;          // Make a vector of strings to hold your wordbank
wordbank.push_back("house");      // Add words to wordbank one-by-one
wordbank.push_back("car");        // ...
wordbank.push_back("tree");       // ...
wordbank.push_back("bicycle");    // ...
wordbank.push_back("shark");      // ...
                   // or add all words at initialization - like:
                   //vector<string> wordbank {"house", "car", "tree", "bicycle", "shark"};

srand (time(NULL));
int random = rand() % wordbank.size();
string word = wordbank[random];   // Copy wordbank[random] into word

Now you can just add new words to wordbank without carrying about how many words it contains and how long the individual words are.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks I think the first suggestion will work although I don't really understand what what the 'srand (time(NULL));' is.
@Stu - The srand is not really important here. Anyway - a short explanation: Random numbers in a computer are not really random. They are calculated in a predictable way. When using random numbers you can give the random-generator a seed (i.e. like a start condition) which determines the sequence of number you'll get from rand. This is what srand does - gives the seed. So if you did srand(1234); you would get the same sequence every time. Using srand (time(NULL)); the sequence depends on the programs start time. So the sequence will be different every time your program runs.
1

To answer your question:

char* word = wordbook[random];

As a side note: you have a serious problem with the way you generate random numbers. How do you guarantee that random never gets larger than 4?

Comments

1

If you can use C++11 then you should at the very least use std::array, but probably std::vector. Then you can use this function

#include <random>
#include <stdexcept>
#include <cstddef>
#include <iterator>

template <typename Container>
typename Container::value_type random_member(const Container& values)
{
    static std::default_random_engine generator {};
    if (values.empty()) throw std::runtime_error {"cannot sample from empty container"};
    std::uniform_int_distribution<size_t> distribution {0, values.size() - 1};
    return *std::next(std::cbegin(values), distribution(generator));
}

Here's how you can use it, in increasing order of sanity:

#include <iostream>
#include <array>
#include <string>
#include <vector>

int main()
{
    std::array<const char*, 5> wordbank {"house", "car", "tree", "bicycle", "shark"};
    std::cout << random_member(wordbank) << std::endl;

    std::array<std::string, 5> a {"house", "car", "tree", "bicycle", "shark"};
    std::cout << random_member(a) << std::endl;

    std::vector<std::string> v {"house", "car", "tree", "bicycle", "shark"};
    std::cout << random_member(v) << std::endl;

    return 0;
}

Comments

0

char arrays can be constructed by either bracer initializer or a string literal.

Here are the two ways to initialize the array :

    char someSequence[5] = {'a','b','c','d','e'}
    char someWord[] = "Hello";

Both initializer methods ca be used with or without the size said explicitly .

You cannot initialize a static array with a char* pointer.

Here's another way to get the same error :

   char* someArray =new char[40];
   char someStaticArray[40] = someArray; // notice the same compile error ?

Comments

0

This line is syntactically wrong. you can't initialize an array as in belowline.

char word[20] = wordbank[random];

if you want to initialize an array at the time of defining it, you've to use brace enclosed { } or " "(const string Ex:"Hello").

In your problem,

Instead of using 1D array, use character pointer to get word form your 2D array wordbank.

This snippet might help you. But try to improve your question. It will give you better answers

int main()
{
     char wordbank[5][20] = {"house", "car", "tree", "bicycle", "shark"};
     int random = (rand() % 5);
     char *word = wordbank[random];
     cout << word;
}

Comments

0
const int size = 5;
const char * wordbank[size] = 
{"house", "car", "tree", "bicycle", "shark"};

const char * word = wordbank[ rand() % size ];

Size is the number of string. Wordbank is an array of string ,its size is 5.word is a string which is the result of a random index. The index is given by the function rand which has a range of 0-4 , so there is no out-range.

2 Comments

Would you mind to add some explanation of your code please? Code only answers aren't useful.
You should add this information to your answer please.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.