为什么我无法在此 cpp 程序中更新我的文本文件?

问题描述 投票:0回答:1

我正在制作这个库存系统,在这个系统中,我正在制作两个文本文件,一个用于存储详细信息,另一个用于临时存储更新的详细信息。我是一个初学者,所以我在主要做这样的项目的同时学习一些东西。

我想将updatedinventory.txt中的信息更新为inventory.txt。例如,如果我将 p1 的产品数量从 2 更新为 20,那么我想在 inventory.txt 而不是 updateinventory.txt 中进行这些更改。 这是源代码:

#include <iostream>
#include <fstream>
#include <cstdlib>

using namespace std;

int main(){
    string product_name;
    int product_price, product_num;

    cout<< "enter the product name: ";
    cin>> product_name;

    ifstream infile("inventory.txt", std::ios_base::app);
    ofstream outfile("updatedinventory.txt" );

    string storedproductname;

    while(infile >> storedproductname >> product_num >> product_price) 
    {   
        if (storedproductname == product_name){
            
            cout << "product exist already...update number of products: ";
            cin >> product_num;
            outfile << storedproductname << ' ' << product_num << ' ' << product_price << endl;
            cout << "details updated...";
            return 0;
        }
        //else {outfile << storedproductname << ' ' << product_num << ' ' << product_price << endl;}
            
        } 
    
            cout<< "enter the number of products: ";
            cin>> product_num;

            cout << "enter the price of 1 product: ";
            cin>> product_price;
            cout<< "product added...";

            outfile << product_name << ' ' << product_num << ' ' << product_price << endl; 

    infile.close();
    outfile.close();

    remove("inventory.txt");
    rename("updatedinventory.txt","inventory.txt");

    return 0;
}


c++ file c++11 filesystems c++14
1个回答
0
投票

以下似乎是您的代码的工作版本

#include <iostream>
#include <fstream>
#include <cstdlib>

using namespace std;

int main(){
    string product_name;
    int product_price, product_num;

    cout<< "enter the product name: ";
    cin>> product_name;

    ifstream infile("inventory.txt", std::ios_base::app);
    ofstream outfile("updatedinventory.txt" );

    string storedproductname;

    while(infile >> storedproductname >> product_num >> product_price) 
    {   
        if (storedproductname == product_name){
            
            cout << "product exist already...update number of products: ";
            cin >> product_num;
            outfile << storedproductname << ' ' << product_num << ' ' << product_price << endl;
            cout << "details updated...";
        }
        else {
            outfile << storedproductname << ' ' << product_num << ' ' << product_price << endl;
        }
            
    } 

    infile.close();
    outfile.close();

    remove("inventory.txt");
    rename("updatedinventory.txt","inventory.txt");

    return 0;
}
© www.soinside.com 2019 - 2024. All rights reserved.