我目前正在尝试编写一个程序,可以将文件中的对象读取到数组中。在程序末尾,我希望将数组内容写入文件中。迄今为止,我在读取文件的方法上已经有了一定的成功,我的写入文件方法也基本完成。它可以工作,但同时也输出了由默认构造函数创建的数组的新元素。有没有办法防止这些默认对象被写入文件,或者最好是在第一次创建时就避免它们的生成?
以下是我的类中成员变量、默认构造函数和方法。
以下是我的类中成员变量、默认构造函数和方法。
private:
//Member variables
string stockCode;
string stockDesc;
int currentLevel;
int reorderLevel;
//Defining Default Constructor
Stock::Stock()
{
}
//Defining function for items to file
void Stock::writeToFile(ofstream& fileOut)
{
fileOut << stockCode << " ";
fileOut << stockDesc << " ";
fileOut << currentLevel << " ";
fileOut << reorderLevel << " ";
}
//Defining function for reading items in from the file
void Stock::readFromFile(ifstream& fileIn)
{
fileIn >> stockCode;
fileIn >> stockDesc;
fileIn >> currentLevel;
fileIn >> reorderLevel;
}
这是我的主函数
#include <iostream>
#include <string>
#include <fstream>
#include "Stock.h"
using namespace std;
int main()
{
const int N = 15;
Stock items[N];
int option = 0;
ifstream fileIn;
fileIn.open("Stock.txt");
for (int i = 0; i < N; ++i)
items[i].readFromFile(fileIn);
fileIn.close();
cout << "1.Display full stock list." << endl;
cout << "9.Quit." << endl;
cout << "Please pick an option: ";
cin >> option;
switch (option)
{
case 1:
{
cout << "stockCode" << '\t' << "stockDesc" << '\t' << '\t' << "CurrentLevel" << '\t' << "ReorderLevel" << endl;
cout << "------------------------------------------------------------------------------" << endl;
for (int i = 0; i < N; ++i)
{
cout << items[i].getCode() << '\t' << '\t';
cout << items[i].getDescription() << '\t' << '\t' << '\t';
cout << items[i].getCurrentLevel() << '\t' << '\t';
cout << items[i].getReorderLevel() << endl;
}
break;
}
case 9:
ofstream fileOut;
fileOut.open("Stock.txt");
for (int i = 0; i < N; ++i)
{
items[i].writeToFile(fileOut);
}
break;
}
return 0;
}
std::vector<Stock> items;
并使用push_back()
来填充它,而不是使用Stock items[N];
。 - πάντα ῥεῖ