好吧,这是一个很难用谷歌搜索的问题。我想要的是一旦用户在库存数组中输入 10 个项目,我希望它清除控制台并讲述一个故事。我试过了,但无论数组中有多少项目,它都会显示故事,因为我将数组定义为最多 10 个。我还试图找到一种方法来交换数组中的项目。我的意思是我希望控制台询问用户是否愿意将{item which is already in the array}换成{item2} y或n?
问题是在故事示例中输出时,它不显示项目名称,只显示数组中的位置。显示“你想用 1 交易附魔剑”。然后,如果你点击是,它不会将它添加到数组中。无论如何它也绕过了我的谢谢
void tellStory(InventoryRecord list[], int& size)
{
int numOfRecs = size;
int pos = rand()%numOfRecs; //Generate a random position of the item
//Generate item to trade, I'll refer to it as "Item
int TRADE_CHANCE = 0;
const string str = "Enchanted Sword";
InventoryRecord recList[MAX_SIZE];
if (numOfRecs == MAX_SIZE) {
system("cls");
cout << "So your ready to begin your quest!" << endl << endl;
cout << "Before you begin I would like the opportunity to trade you a rare item!" << endl << endl;
cout << "Would you like to trade" << pos << "for" << str << "?" << endl << endl;
cout << "Yes or No? ";
cin >> choice;
if (toupper(choice) == 'Y')
(rand()%100 < TRADE_CHANCE);
(recList[pos], str);//Here add the trading stuff, which is some text, user input(y/n) and replacing realist[pos] = Item, etc
}
else {
cout << "Thanks anyways!" << endl << endl;
system("pause");
}
system("cls");
}
最佳答案
事情是你没有在任何地方检查库存是否已满。你可能想要替换
案例“A”:addData(recList, numOfRecs);休息;
如果你只想讲一次故事
case 'A':
if (numOfRecs == MAX_SIZE-1) {
addData(recList, numOfRecs);
//TELL STROY HERE
} else{
addData(recList, numOfRecs);//If you want to tell a story only once
}
break;
如果你想随时讲故事
case 'T': //TEll story
if (numOfRecs == MAX_SIZE) {
//TELL STORY HERE
}
break;
或者,尽管这很烦人,但在每次操作后,检查库存中是否有 10 件元素并显示故事
现在进行交易,假设您希望他们交易他们拥有的元素,对于您将生成的随机元素,请使用: pos = rand()%numOfRecs;//生成元素的随机位置 现在,如果您想生成“随机”交易建议:
if (rand()%100 < TRADE_CHANCE) {
int pos = rand()%numOfRecs; //Generate a random position of the item
//Generate item to trade, I'll refer to it as "Item"
SuggestTrade(recList[pos], Item);//Here add the trading stuff, which is some text, user input(y/n) and replacing realist[pos] = Item, etc
}
如果你要交易的项目,它实际上是同一个数组中的位置交换:
int pos = rand()%numOfRecs; //Generate a random position of the item
int pos2;
do {
pos2 = rand()%numOfRecs; //Generate a random position of the item
}while (pos2 == pos);
//Actually "swapping"
InventoryRecord tmp = recList[pos];
recList[pos] = recList[pos2];
recList[pos2] = tmp;
希望对您有所帮助!
关于C++ 数组循环问题仍然需要帮助,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18907287/