gpt4 book ai didi

C++ 程序在运行时重新使用变量或创建变量?

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

无论如何,您是否可以将数据存储在 C++ 控制台应用程序中,将其传输到不同的变量,然后重用该变量?

为什么我想要这个:我想让用户输入订单的订单详细信息,然后让程序能够存储它们,以便程序可以重新创建另一个订单。

当前代码:

int quant;
int cost;
int selling;
int profit;
NewOrder:
cout <<""<< endl;
cout << "Enter an Order Number: " << flush;
getline(cin, ord);

cout << "Enter a Product ID: " << flush;
getline(cin, Prod);

cout << "Enter a Quantity: " << flush;
cin>>quant;
Pricing:
cout << "Enter a cost per unit: " <<char(156) << flush;
cin >> cost;

cout << "Enter a selling price per unit: " <<char(156) << flush;
cin >> selling;

Sleep(2000);
cout << endl;
cout << "Your order Details are:" << endl;
cout << "Order Number: " << ord << endl;
cout << "Product: " <<Prod << endl;
cout << "Quantity:" << quant << endl;
cout << "Total Cost: " <<char(156) << (quant*cost) << endl;
cout << "Total Selling Price: " <<char(156)<< (quant*selling) << endl;

profit = ((quant*selling) - (quant*cost)); //Assigning a value to profit.

cout << "Total Profit: " <<char(156)<< profit << endl;
if (profit < 0) {
cout << "You have a negative profit. Please change your pricing." << endl;
Sleep(3000);
goto Pricing; }

目前,它允许用户输入一个订单的详细信息,然后显示它们。我想要它,这样程序就可以输入多个订单,然后按订单号可以召回它们。我可以使用程序内存来​​执行此操作还是需要将其设置为 SQL DB?

如果是这样,我该如何设置 SQL 连接?

如果我可以在内存中完成,怎么做?我一直在四处寻找,但无法在运行时创建和声明变量。

最佳答案

您可以使用 vector 跟踪所有订单:

struct Product {
//Add additional fields you need here
int quant;
int cost;
int selling;
int profit;
};

int main() {
std::vector<Product> products;

while (stillAddingProducts) {
//Get all the data from the user
Product p;
p.quant = 10; //example you should get this from the user

//Insert the product based on the information received
products.push_back(p);
}

//Perhaps iterate through all products and display information
for (const auto& e : products) {
std::cout << "Quantity: " << e.quant << std::endl;
}
}

有了这个,您将在每次迭代中拥有一个“全新”的 Product 对象。在旁注中,尝试 avoid在您的代码中使用 goto

关于C++ 程序在运行时重新使用变量或创建变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22847295/

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