2017-09-16 94 views
0

我希望有人能幫助我。以下是我目前的代碼。請溫和一點,這是我第一次使用C++編寫的程序,距離我最後一次碰觸C已經有一年多了。是的,這是爲了作業〜我已經使用這個頁面足以知道它被問了很多;)帶用戶輸入的C++文本數組,然後打印輸入

我有一個問題,並努力尋找一些適度的幫助,是如何創建一個數組來存儲用戶輸入文本?

從代碼流程中可以看出:我詢問用戶想要購買多少物品......然後決定循環,詢問用戶購買的物品名稱,每件物品的成本以及總數(量。數學部分我很好〜我有購買的總項目和運行小計相當準確地打印出來。但是,我想要做的是按順序打印購買的商品的名稱。

目前代碼輸出:

How many items do you want to enter? 3 
What is the item name? Honey 
What is the unit price for Honey? 5.99 
How many purchased? 3 
What is the item name? Milk 
What is the unit price for Milk? 2.79 
How many purchased? 2 
What is the item name? chocolate 
What is the unit price for chocolate? 1.97 
How many purchased? 5 

Bill Date: 
Items Purchased: 10 
Subtotal: 33.4 

在「比爾日期」和「購買的商品」之間我想列出,一行行的(3)購買的物品:蜂蜜,牛奶和巧克力。這是項目名稱的存儲和增加,我非常堅持。如果有人能指引我正確的方向,我將不勝感激。而且,請更詳細地解釋如何以及爲什麼,對我來說更好。文本/字符數組和我僅僅是熟人,而數字int數組和我正在喝酒夥伴。

謝謝! :d


所需的代碼輸出:

Bill Date: 
Honey 
Milk 
chocolate 
Items Purchased: 10 
Subtotal: 33.4 

我的代碼:?

#include <iostream> 
#include <iomanip> 
#include <cstdlib> 
#include <cstring> 
#include <time.h> 

using namespace std; 

int main() 
{ 
    int itemCount = 0, i, itemQty; 
    int numOfItems = 0; 
    char itemName[25]; 
    double itemCost; 
    double itemSub; 
    double subtotal = 0; 

    cout << "How many items do you want to enter? "; 
    cin >> itemCount; 

for(i = 0; i < itemCount; i++) 
{ 
    cout << "What is the item name? "; 
    cin >> itemName; 
    cout << "What is the unit price for " << itemName << "? "; 
    cin >> itemCost; 
    cout << "How many purchased? "; 
    cin >> itemQty; 

    numOfItems = numOfItems + itemQty; 
    itemSub = itemQty * itemCost; 
    subtotal = subtotal + itemSub; 
} 

cout << "\n\tItems Purchased: " << numOfItems; 
cout << "\n\tSubtotal: " << subtotal << "\n"; 
} 
+0

我會建議使用成員'itemCost'' itemName'和'itemQty'結構。使'itemName'成爲'std :: string'。將項目數組更改爲上述結構的「std :: vector」,並在打印其元素之前使用std :: sort對向量進行排序 –

回答

0

什麼要purhcased項目數量最多的...我想這是100。 。而不是製作一個字符數組,您可以創建一個字符串數組,將char itemName[25];行更改爲string itemName[100];,然後在for循環中將itemname的輸入和輸出更改爲cin >> itemName[i]; cout << "What is the unit price for " << itemName[i] << "? "; 然後你可以輸出項目的名稱在最後這樣:

for(int i=0;i<itemCount;i++) 
    { 
    cout<<endl<<itemName[i]; 
    } 
cout << "\n\tItems Purchased: " << numOfItems; 
      cout << "\n\tSubtotal: " << subtotal << "\n";