使用用户输入来定义数组

时间:2015-03-04 20:26:21

标签: c++ arrays

我有一个项目,我需要创建一个带结帐功能的购物清单。我正在尝试使用用户输入创建一个数组。他们提供了他们购买的产品数量,我需要使用它来定义数组的大小。

#include <iostream>
#include <string>
#include <fstream>

using namespace std;

struct shopList {
    double pluCode;
    string product;
    int saleType; // 0 = per unit, 1 = per pound
    double price;
    double inventory;


};

int main(){

    char line[255];
    const int items = 0;
    int n;

    ofstream outfile;
    outfile.open("products.txt");

    cout << "How many items in your checkout: ";
    cin >> items;

    shopList shop[items];

    for (n = 0; n < items; n++) {
        cout << "Enter the PLU code: ";
        cin >> shop.pluCode;
        outfile << shop.pluCode << " ";

        cout << "Enter product name: ";
        cin >> shop.product;
        outfile << shop.product << " ";

        cout << "Enter the price type (0 for per unit, 1 for per pound): ";
        cin >> shop.saleType;
        outfile << shop.saleType << " ";

        cout << "Enter the price of the product: ";
        cin >> shop.price;
        outfile << shop.price << " ";

        cout << "How much will you purchase: ";
        cin >> shop.inventory;
        outfile << shop.inventory << " " << "\n";

    }



    outfile.close();

    ifstream infile;
    infile.open("products.txt");
    infile.getline(line, 255);
    cout << line << endl;
}

1 个答案:

答案 0 :(得分:1)

有可能,你只需改变你的声明;

int items = 0;  cin&gt;&gt;物品;

shopList *shop =  new  shopList [items];