2014-04-03 74 views
1

無論如何,您是否可以將數據存儲在C++控制檯應用程序中,將其轉移到不同的變量,然後重用該變量?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

http://en.cppreference.com/w/cpp/container - 也是http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list –

+0

爲什麼while(profit <= 0)'時使用'goto'而不是''? –

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

有了這個,你將有一個「新鮮」產品對象每次迭代。在旁註中,在代碼中使用goto嘗試avoid