簡體   English   中英

具有用戶輸入的C ++文本數組,然后打印輸入

[英]C++ Text Array with User Input, then printing the input

我希望有人可以幫助我。 下面是我當前的代碼。 請放心,這是我的第一個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)件商品:蜂蜜,牛奶和巧克力。 我非常堅持使用的是項目名稱的存儲和遞增。 如果有人能指出我正確的方向,我將不勝感激。 而且,請您越冗長地解釋方式和原因,對我來說就更好。 文本/字符數組和我只是熟人,而數字整數數組和我在喝酒。

謝謝!! :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";
}

我想購買的最大物品數量是多少?...我想它是100。除了代替一個char數組,您還可以創建一個字符串數組,因此更改了char itemName[25]; string itemName[100]; 然后在for循環中,將itemname的輸入和輸出更改為cin >> itemName[i]; cout << "What is the unit price for " << itemName[i] << "? "; 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";

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM