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

时间:2014-04-03 19:35:39

标签: c++ variables runtime

无论如何,您是否可以将数据存储在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连接?

如果我能在记忆中做到,怎么样?我一直在四处寻找,我不能在运行时创建和声明变量。

1 个答案:

答案 0 :(得分:0)

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

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

有了这个,你就会有一个新鲜的&#39;每次迭代都有产品对象。在旁注中,尝试使用代码中的goto avoid