1

My code:

void Block::word()
{
    std::string worda[] = {"cat","owl","cow"};
    std::string wordb[] = {"apple","power","block"};
    std::string wordc[] = {"account","extreme","kingdom"};
    std::string wordd[] = {"adjective","undefined","pineapple"};

    srand(time(0));
    fnwords[0] = worda[rand() % 3 + 1];
    fnwords[1] = wordb[rand() % 3 + 1];
    fnwords[2] = wordc[rand() % 3 + 1];
    fnwords[3] = wordd[rand() % 3 + 1];

    for (int d=0; d<4; d++){
          std::cout << fnwords[d] << std::endl;
      }
}

int main()
{
    Block obj;
    obj.word();
    return 0;
}

Here the first index of array fnwords must contain a random word from array worda, second index from wordb, and so on.

But it gives error sometimes that program.exe has stopped working.

And it initializes array like this:

-cow
-cat
-kingdom
-undefined
4
  • 11
    Indexing starts at 0, rand() % 3 gives 0, 1, or 2. Don't + 1 Commented Jan 14, 2020 at 7:40
  • Where are Block and fnwords defined? Where are the includes for <string>, <iostream> and <cstdlib>? Please edit your code to make it a minimal reproducible example of your problem. Commented Jan 14, 2020 at 8:51
  • Well it was a very big code to write here.... Commented Jan 14, 2020 at 8:58
  • rand () % 3 worked for me :) Commented Jan 14, 2020 at 8:58

1 Answer 1

1

The problem seems to be related to rand() call. You are using arrays with length of 3. However, rand()%3 returns one of the following set: {0, 1, 2} which are the only valid values to index your array. When you +1 to this index, it gives you {1, 2, 3} where index 3 is an invalid index.

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

1 Comment

@Mr.Developer Good news :)

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.