我目前正在研究自动售货机计划。但是,我无法弄清楚如何询问用户输入并打印出选项和价格。这是我的代码的一部分,我的问题是:我如何要求用户在main()中输入并从Base子类中获取选项。
提前谢谢。
class Product
{
protected:
string product_description;
int itemCost = 0;
public:
virtual void consume(void)
{
}
virtual int cost(void) { return this->itemCost; }
virtual string description(void) { return product_description; }
virtual Product* ReturnHighestCostItem(void)
{
return this;
}
virtual void RemoveHighestCostItem(void)
{
return;
}
};
class Base : public Product
{
public:
Base(int option)
{
if (option == 1)
{
this->product_description = "Plain";
this->itemCost = 100;
}
else if (option == 2)
{
this->product_description = "Spicy";
this->itemCost = 150;
}
else if (option == 4)
{
this->product_description = "Chocolate";
this->itemCost = 200;
}
else if (option == 8)
{
this->product_description = "Coconut";
this->itemCost = 200;
}
else if (option == 16)
{
this->product_description = "Fruity";
this->itemCost = 200;
}
}
};
int main()
{
Product obj;
cout << "The Available descriptions are:" << obj.description()<< endl;
return 0;
}
答案 0 :(得分:0)
自动售货机的输入受限制。除非用户输入有效地址,否则它不应占用用户的钱。我使用的大多数自动售货机都带有一个指定行的字母,后跟一个指定列的数字,即左上角通常为A0
。右侧的项可能是A1
或A2
等。自动售货机中的每个Product
都需要映射到其中一个地址。用户可能会输入金钱(或信用卡?),然后输入他们的选择。您必须验证他们的选择,即他们指定的地址对特定产品有效,并且他们有足够的信用来购买该产品。为了更好地显示您的要求,您可以参考此图片。
您应该熟悉std::cin
并获取用户输入。您可以将输入存储为std::string
,以便于验证和查找关联的Product
至vend。
#include <iostream>
#include <iomanip>
#include <string>
#include <limits>
int main()
{
double credits; ///< user input for credits
std::string selection; ///< user input for vending address
std::cout << "Welcome to vending machine!" << std::endl;
std::cout << "Please input credits to purchase an item ex. 1.00 or 5.00" << std::endl;
std::cout << "Ready -> " << std::flush;
// we need to enforce that the user entered a number here
while(!(std::cin >> credits))
{
std::cout << "Invalid value!\nPlease input credits to purchase an item! ex. 5.00" << std::endl;
std::cout << "Ready -> " << std::flush;
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}
// (optional) format output stream for displaying credits i.e. 1.00
std::cout << std::fixed;
std::cout << std::setprecision(2);
std::cout << "Please make a selection (A-J,0-8) ex. B6 or A2" << std::endl;
std::cout << "Ready (cr. " << credits << ") -> " << std::flush;
// any input can be a std::string so we will need to post-process to make sure
// it's a valid input (format is correct and the product exists to vend)
std::cin >> selection;
// TODO: validate the users selection!
return 0;
}