C ++ Array Loop问题仍然需要帮助

时间:2013-09-20 00:54:19

标签: c++ arrays

好吧这对google来说是个难题。我想要的是,一旦用户在库存数组中输入10个项目,我希望它清除控制台并讲述故事。我尝试但是它会显示故事,无论数组中有多少项,因为我将数组定义为最大值10.我也试图找到一种方法来交换数组中的项目。我的意思是,我希望控制台询问用户是否愿意为{item2} y或n交换{已存在于数组中的项}?

问题是它没有显示项目名称只是数组中的位置,在故事示例中输出。 “你想交换魔法剑吗”会显示出来。然后,如果你点击是,它不会将它添加到数组。它还绕过我的谢谢

  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");
    }

1 个答案:

答案 0 :(得分:3)

事情是你没有在任何地方检查库存是否已满。您可能想要替换

case'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;

希望它有帮助!