【发布时间】:2015-02-21 09:42:00
【问题描述】:
我的问题如下:
我想使用重载的 >> 运算符将文件中的值读取到名为 Voter 的特定类的动态数组中。 然后,我想将我的结果导出到屏幕上,用另一个重载的
使用普通数组,我得到了即时结果,但在动态化方面遇到了困难。 我在论坛上读到向量可能是一种更好的方法,但我想了解我在这方面做错了什么。
谢谢!
详情:
该文件有 3 个用空格分隔的“值”: id(string) nr(int) (1 or 0)bool
代码摘录:
string RollFileName = "VotersRoll.dat";
ifstream inFile_VotersRoll;
inFile_VotersRoll.open(RollFileName);
if(inFile_VotersRoll.fail())
{
printf("The VotersRoll.dat file failed to open.\n");
exit(1);
}
//connect to in file
int numberOfEntries = 0;
Voter testVoter;
while(inFile_VotersRoll>>testVoter)
{
numberOfEntries++;
}
//get number of voter objects from file
typedef Voter* VoterArrayPntr;
VoterArrayPntr rollArray;
rollArray = new Voter[numberOfEntries];
//create dynamic arrray for voter objects
while (inFile_VotersRoll>>*rollArray) {
cout << *rollArray;
}
类(摘录):
class Voter
{
public:
friend istream& operator>>(istream &inP, Voter &voterP);
friend ostream& operator<<(ostream &outP,const Voter &voterP);
private:
string id;
int nr_times_voted;
bool voted;
}
好友功能:
istream& operator>>(istream &inP,Voter &voterP)
{
inP >> voterP.id >> voterP.nr_times_voted >> voterP.voted;
return inP;
}
ostream& operator<<(ostream &outP,const Voter &voterP)
{
outP << voterP.id << voterP.nr_times_voted << voterP.voted;
return outP;
}
【问题讨论】:
-
您的输入、输出和错误信息是什么?请阅读this。
-
感谢 philipxy - 没有真正收到任何错误消息:我正在阅读此内容(VotersRoll.dat 文件数据):19810102009 1 0 19792003008 2 0 19851010890 3 1 19900909897 2 0 19561812567 6 1 目前只有输出:程序以退出代码结束:0
-
@Gpoo 请编辑您的问题以提供此类附加信息。如您所见,它在评论中的可读性不是很好。
-
第一次阅读后是否“倒回”文件?
-
@JoachimPileborg 感谢 Joachim。不,我没有。这似乎是问题所在。关于如何实现这一目标的任何指导?刚开始接触 c++,所以还在学习细节。
标签: c++ arrays dynamic operators