gpt4 book ai didi

c++ - 自动售货机c++

转载 作者:太空宇宙 更新时间:2023-11-04 12:52:00 25 4
gpt4 key购买 nike

我目前正在研究自动售货机程序。但是,我无法弄清楚如何要求用户输入并打印出选项和价格。这是我的代码的一部分,我的问题是:我如何要求用户在 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;
}

最佳答案

自动售货机的输入有限制。除非用户输入有效地址,否则它不应该拿走用户的钱。我用过的大多数自动售货机都采用一个字母来指定行,后跟一个数字来指定列,即左上角通常是 A0。右侧的项目可能是 A1A2 等。自动售货机中的每个 Product 都需要映射到这些地址之一.用户可能会输入金钱(或信用卡?),然后输入他们的选择。您将必须验证他们的选择,即他们指定的地址对特定产品有效,并且他们有足够的信用来购买该产品。为了更好地可视化您的要求,您可以引用这张图片。 vending machine input

您应该熟悉 std::cin 和获取用户输入。您可以将输入存储为 std::string,以便于验证和查找关联的 Product 以进行销售。

#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;
}

关于c++ - 自动售货机c++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48669567/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com