[英]How can I pass values from different multiple arrays to a new single array?
我的代碼:
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;
}
這里陣列的第一索引fnwords
必須包含從陣列的隨機字worda
,第二索引從wordb
,依此類推。
但有時它會出錯,program.exe 已停止工作。
它像這樣初始化數組:
-cow
-cat
-kingdom
-undefined
問題似乎與rand()
調用有關。 您正在使用長度為 3 的數組。但是, rand()%3
返回以下集合之一:{0, 1, 2} 這是唯一可以為您的數組建立索引的有效值。 當您對該索引+1
,它會給您 {1, 2, 3} ,其中索引 3 是無效索引。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.