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
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.