[英]How can I pass values from different multiple arrays to a new single array?
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.这里阵列的第一索引
fnwords
必须包含从阵列的随机字worda
,第二索引从wordb
,依此类推。
But it gives error sometimes that program.exe has stopped working.但有时它会出错,program.exe 已停止工作。
And it initializes array like this:它像这样初始化数组:
-cow
-cat
-kingdom
-undefined
The problem seems to be related to rand()
call.问题似乎与
rand()
调用有关。 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.您正在使用长度为 3 的数组。但是,
rand()%3
返回以下集合之一:{0, 1, 2} 这是唯一可以为您的数组建立索引的有效值。 When you +1
to this index, it gives you {1, 2, 3} where index 3 is an invalid index.当您对该索引
+1
,它会给您 {1, 2, 3} ,其中索引 3 是无效索引。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.