提问者:小点点

我在C++文件上遇到了一些问题


我需要你帮我处理这个代码。 这是一个面包店管理系统,我在将产品添加到文件(一个txt文件)时遇到了问题,每次添加产品时,它只显示产品的名称,其余的都是奇怪的符号,系统无法识别,这也影响了buy()功能。

  class addProduct{
    char name[100];
    Date product_date, validity;

    public:
        float price, discount, total;
        int number, quantity, day, month, year;
        Date sales_date;
        void add();
        int disc();
        
};

ofstream file;
addProduct product;
addProduct quant;

void addProduct::add(){
            cout<<"Please enter the product name: ";
            cin.ignore();
            cin.getline(name, 100);
            cout<<"Please enter the product number: ";
            cin>>number;
            cout<<"Please enter the product quantity: ";
            cin>>quantity;
            cout<<"Please enter the price: ";
            cin>>price;
            cout<<"Please enter the discount(%): ";
            cin>>discount;
            cout<<"Please enter the product date(day, month, year): ";
            product_date.enter();
            cout<<"Please enter the validity(day, month, year): ";
            validity.enter();
}

int addProduct::disc(){
    discount = (price*discount)/100;
    total = price - discount;
    return total;
}

void add_product(){
    ofstream file;
    file.open("BakeSale2.txt", ios::app);
    product.add();
    file.write((char*)&product,sizeof(addProduct));
    file.close();
}

输出


共2个答案

匿名用户

您不能简单地将您的类转换为char*在这行中:

file.write((char*)&product,sizeof(addProduct));

我建议您使用重载输出运算符的可能性(<<)

匿名用户

您应该正确设置输出的格式。 file.write不能用于像这样的专有类型。 现在,它只是转储对象的内存。

您可以这样做:

file.write("name: ");
file.write(product.name);
file.write('\n');
file.write("price: ");
file.write(product.price);
etc...

相关问题


MySQL Query : SELECT * FROM v9_ask_question WHERE 1=1 AND question regexp '(c++|文件|遇|到了|一些问题)' ORDER BY qid DESC LIMIT 20
MySQL Error : Got error 'repetition-operator operand invalid' from regexp
MySQL Errno : 1139
Message : Got error 'repetition-operator operand invalid' from regexp
Need Help?