为何无法更新库存系统中的inventory.txt文本文件?
库存系统代码修正方案
问题排查
你的代码存在几个核心问题,导致无法将更新正确同步到inventory.txt:
- 文件打开模式错误:用
std::ios_base::app打开原库存文件,会让读取指针直接跳到文件末尾,根本读不到现有产品数据。 - 提前终止程序:找到匹配产品更新后直接
return 0,原库存里的其他产品都没写入临时文件,最终替换后这些数据会全部丢失。 - 遗漏原有产品写入:注释掉的
else块是关键,没它的话只有被更新的产品或新添加的产品会被保留,其余原有产品都没了。
修正后的代码
#include <iostream> #include <fstream> #include <cstdlib> using namespace std; int main(){ string product_name; int product_price, product_num; cout << "输入产品名称: "; cin >> product_name; // 用默认只读模式打开原库存文件,移除错误的追加模式 ifstream infile("inventory.txt"); ofstream outfile("updatedinventory.txt"); string storedproductname; bool product_found = false; while(infile >> storedproductname >> product_num >> product_price) { if (storedproductname == product_name){ cout << "产品已存在...请更新产品数量: "; cin >> product_num; outfile << storedproductname << ' ' << product_num << ' ' << product_price << endl; cout << "信息已更新..."; product_found = true; } else { // 将未修改的原有产品写入临时文件 outfile << storedproductname << ' ' << product_num << ' ' << product_price << endl; } } if (!product_found) { cout << "输入产品数量: "; cin >> product_num; cout << "输入单个产品价格: "; cin >> product_price; cout << "产品已添加..."; outfile << product_name << ' ' << product_num << ' ' << product_price << endl; } infile.close(); outfile.close(); // 替换原库存文件 remove("inventory.txt"); rename("updatedinventory.txt", "inventory.txt"); return 0; }
修改说明
- 修复文件打开模式:去掉
std::ios_base::app,让ifstream以默认只读模式读取原库存文件,确保能获取所有现有数据。 - 新增产品存在标志:用
product_found标记是否找到目标产品,避免提前终止程序导致数据丢失。 - 恢复原有产品写入逻辑:确保所有未修改的产品都被写入临时文件,完整保留库存数据。
- 调整流程顺序:遍历完所有原有产品后再处理新产品添加,保证所有数据都被正确处理。
这样修改后,当你更新p1的数量时,所有原有产品(包括更新后的p1)都会被写入updatedinventory.txt,随后通过删除重命名操作替换原inventory.txt,修改会正确同步到主库存文件中。
内容的提问来源于stack exchange,提问作者Kartik
相关产品推荐
相关产品推荐

