使用用户输入定义数组

Using user input to define array

本文关键字:定义 数组 输入 用户      更新时间:2023-10-16

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

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

这是可能的,您只需要像那样更改声明;

int个项目=0;cin>>项目;

shopList *shop =  new  shopList [items];