我目前正在尝试编写一个程序,该程序可以将对象从文件读取到数组中。在程序快结束时,我希望它将数组的内容写出到文件中。到目前为止,我已经取得了一定程度的成功,我的文件读取方法似乎没有任何问题,并且在某种程度上我知道我已经接近我的写入文件方法。它有效,但它也输出由默认构造函数创建的数组的新元素。有什么方法可以阻止将这些默认对象写入文件,或者更好的是,首先阻止它们的创建?
这是我的类中的成员变量、默认构造函数和方法
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;
}
最佳答案
您可以跟踪存储在文件中的项目数量,并最终通过将该数字存储为文件中的第一个值来添加到代码中:
int num_items = 0;
// keep track of number of items in code
// when writing to the file, first write num_items
fileOut << num_items << " ";
读入时,先读入num_items:
fileIn >> num_items;
然后,使用 std::vector
而不是数组存储和添加元素(您可以使用 reserve()
预先将其大小设置为 num_items
以防止重新分配)。
关于c++ - 从文件中将对象读入数组,反之亦然,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34839111/