读取文件每行生成独立Cost类对象失败问题求助
问题分析与解决方案
核心问题
你的代码之所以会重复存入第一行数据,是因为**itemStr向量在处理完每一行后没有清空**。后续行拆分的内容会不断追加到这个向量中,而你始终取at(0)至at(3)的元素,这些元素始终是第一行的数据。
另外你的Cost构造函数存在潜在错误:this->getName() = name和this->getUnit() = unit这两行无效——如果getName()是返回成员变量的副本(这是常规写法),赋值给返回值不会修改类的实际成员;如果是返回引用,这种写法也不符合编码规范。
修正后的代码
第一步:修复Cost构造函数
假设基类Item的name和unit是protected成员,或者你可以通过setter方法修改:
Cost::Cost(string name, double cost, string unit, double qty) : Item(name, unit) { // 直接赋值给成员变量(如果基类成员可访问) this->name = name; this->cost = cost; this->unit = unit; this->qty = qty; // 若基类提供setter方法,更推荐: // setName(name); // setUnit(unit); }
第二步:修复文件读取逻辑
#include <fstream> #include <sstream> #include <vector> #include <string> #include <iostream> using namespace std; int main() { ifstream inFile("data.txt"); if (!inFile.is_open()) { cerr << "无法打开文件data.txt" << endl; return 1; } string line, word, name, unit; double cost = 0.0, qty = 0.0; vector<string> itemStr; vector<Cost> itemObj; const char delim = ','; // 根据你的实际分隔符修改,比如空格、制表符等 // 直接循环读取每一行,移除多余的外层while(inFile) while (getline(inFile, line)) { itemStr.clear(); // 关键:处理新行前清空容器 stringstream stream(line); while (getline(stream, word, delim)) { itemStr.push_back(word); } // 增加字段数量校验,避免越界访问 if (itemStr.size() >= 4) { name = itemStr.at(0); cost = stod(itemStr.at(1)); unit = itemStr.at(2); qty = stod(itemStr.at(3)); Cost c(name, cost, unit, qty); itemObj.push_back(c); } else { cerr << "行格式错误,跳过:" << line << endl; } } inFile.close(); return 0; }
关键修正点
- 清空容器:每次处理新行前调用
itemStr.clear(),确保容器只保存当前行的拆分字段。 - 移除冗余循环:外层的
while(inFile)完全多余,while(getline(inFile, line))已经能完整读取每一行。 - 增加错误校验:添加文件打开状态判断和行字段数量校验,避免程序崩溃或处理无效数据。
- 修复构造函数赋值:直接操作成员变量或使用setter方法,确保初始化生效。
内容的提问来源于stack exchange,提问作者kez
相关产品推荐
相关产品推荐

