【发布时间】:2016-01-17 00:42:47
【问题描述】:
我目前正在尝试编写程序的一部分,以将数组中的对象读取到文本文件中,反之亦然。我可以让它将对象输出到一个看似没有问题的文件,但是当我尝试将文本文件中的数据读入一个空数组时,它会将最后一个对象放在第一个对象应该在的位置,并将所有其他对象留空。我哪里出错了?
这是我的课程代码
//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)
{
while (fileIn >> stockCode >> stockDesc >> currentLevel >> reorderLevel)
{
fileIn >> stockCode;
fileIn >> stockDesc;
fileIn >> currentLevel;
fileIn >> reorderLevel;
}
}
这是我在 main 中的代码
#include <iostream>
#include <string>
#include <fstream>
#include "Stock.h"
using namespace std;
int main()
{
Stock items[4];
int option = 0;
cout << "1.Display full stock list." << endl;
cout << "Please pick an option: ";
cin >> option;
switch (option)
{
case 1:
cout << "stockCode" << '\t' << "stockDesc" << '\t' << '\t' << "CurrentLevel" << '\t' << "ReorderLevel" << endl;
cout << "------------------------------------------------------------------------------" << endl;
ifstream fileIn;
fileIn.open("Stock.txt");
for (int i = 0; i < 4; i++)
{
items[i].readFromFile(fileIn);
cout << items[i].getCode() << '\t' << '\t';
cout << items[i].getDescription() << '\t' << '\t' << '\t';
cout << items[i].getCurrentLevel() << '\t' << '\t';
cout << items[i].getReorderLevel() << endl;
}
}
return 0;
}
【问题讨论】:
-
值是什么类型?
-
字符串 stockCode,字符串 stockDesc,int currentLevel,int reorderLevel