【发布时间】:2015-02-13 02:15:27
【问题描述】:
我遇到的问题是提示用户输入控制台窗口上出现的任何项目,然后我必须检查该字符串是否有效。如果有效,我必须附加该字符串,显示玩家库存中出现的所有物品并相应地扣除玩家的钱。
问题从 playerInput 函数开始。
#include <iostream>
#include <iomanip>
#include <cctype>
#include <string>
#include <algorithm>
using namespace std;
const int items = 5;
const string ShopInventory[items] = {"Helms", "Boots", "Swords", "Axes", "Leather Armors"};
const int ItemPrices[items]= {10, 5, 20, 30, 50};
void PrintShop();
int PlayerInput(string [], int&);
int main()
{
string PlayerInventory[items];
int playerMoney = 100;
char Response;
cout << "\t\tWelcome traveler to my lovely shop. \n";
cout << "\nFeel free to browse many of the wonderful items within";
cout << " this store. " << endl;
PrintShop();
while(toupper(Response) != 'N')
{
cout << PlayerInput(PlayerInventory, playerMoney);
cout << "\nIs there anything else that you would like to buy? ";
cout << "Enter n or N to quit.\nElse enter y or Y to continue. ";
cin >> Response;
while(toupper(Response) != 'Y' && toupper(Response) != 'N')
{
cerr << "\nSorry, wrong input. Please try again. ";
cin >> Response;
}
}
return 0;
}
void PrintShop()
{
cout << endl;
cout << " ***** Shop Inventory ***** " << endl << endl;
cout << "Shop items " << "\t\tPrice Per Item. " << endl << endl;
for(int i=0; i<items; i++)
{
cout << i+1 << ".) " << left << setw(22) << ShopInventory[i];
cout << left << setw(3) << ItemPrices[i] << " Gold" << endl;
}
}
int PlayerInput(string PlayerInventory[], int &playerMoney)
{
string input;
cout << "\nEnter what you would like to buy. ";
getline(cin, input);
while(find(begin(ShopInventory), end(ShopInventory), input) == end(ShopInventory))
{
cout << "\nThe item that you enter isn't in my inventory. ";
getline(cin, input);
}
return playerMoney;
}
【问题讨论】:
-
你说有问题,但你只提供代码,没有说明问题是什么。
-
我的问题是,在验证用户输入的字符串是否出现在 shopinventory 数组中时,我必须将该字符串附加到 playerinventory 数组中,如果不添加来自shopinventory 数组到 playerinventory 数组中。
-
然后我要告诉玩家他有x数量的斧头、头盔、盔甲等。然后我必须从他的钱包中扣除x数量。
-
程序本身没有问题。在尝试将字符串附加到字符串数组时,我刚刚碰到了一堵墙。我在描述中提到的每一件事都是这个程序必须面对的问题。一旦我将验证过的字符串附加到 playerInventory 数组中,我就可以继续处理该程序中的其他问题(即使验证字符串也很难做到)。