【发布时间】:2016-04-22 16:51:14
【问题描述】:
我目前正在尝试编写一个可以将文件中的对象读入数组的程序。在程序快结束时,我希望它把数组的内容写到文件中。到目前为止,我已经取得了一定程度的成功,我从文件方法中读取似乎没有问题,并且在某种程度上我知道我与我的写入文件方法很接近。它可以工作,但它也会输出由默认构造函数生成的数组的新元素。有什么办法可以阻止这些默认对象被写入文件,或者更好的是,首先阻止它们被写入?
这是我的类中的成员变量、默认构造函数和方法
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;
}
【问题讨论】:
-
使用另一个变量跟踪您有多少元素。
-
Stock items[N];最好使用std::vector<Stock> items;并使用push_back()来填充它。
标签: c++ arrays file oop object