基本上我正在尝试创建一个对象向量,但我必须使用我的类Voter的重载输入流运算符创建从文件读取的信息的对象。
主:
#include <cstdlib>
#include <vector>
#include <string>
#include "Voter.h"
#include <iostream>
#include <fstream>
using namespace std;
int main(int argc, char** argv) {
int i = 0;
int idNumber;
string firstName;
string lastName;
string hasVoted;
vector<Voter> VoterVector;
ifstream inFile;
inFile.open("voters.txt");
if(!inFile){
cout << "Unable to open voters.txt" << endl;
}
inFile >> idNumber >> firstName >> lastName >> hasVoted;
while(inFile) {
Voter temp();
temp >> idNumber >> firstName >> lastName >> hasVoted;
VoterVector.push_back(temp);
inFile >> idNumber >> firstName >> lastName >> hasVoted;
}
return 0;
}
选民类:
#ifndef VOTER_H
#define VOTER_H
#include <string>
using namespace std;
class Voter {
public:
Voter();
virtual ~Voter();
friend istream &operator>>(istream &in, Voter &v);
friend ostream &operator<<(ostream &out, Voter &v);
private:
int idNumber;
string firstName;
string lastName;
string hasVoted;
};
Voter::Voter() {
this->idNumber = 0;
this->firstName = '-none-';
this->lastName = '-none-';
this->hasVoted = 'FALSE';
}
Voter::~Voter() {
}
istream &operator>>(istream &in, Voter &v) {
in >> v.idNumber >> v.firstName >> v.lastName >> v.hasVoted;
return in;
}
ostream &operator<<(ostream &out, Voter &v) {
out << v.idNumber << endl << v.firstName << endl << v.lastName << endl << v.hasVoted << endl;
return out;
}
我一直在创建对象并将它们放入向量中时出错。我很确定我的重载和文件读取是否正确完成,只是不确定正确的方法来设置对象的向量。任何帮助表示赞赏。谢谢!
答案 0 :(得分:2)
Voter temp();
这是错误的。它声明了一个函数。
以下是创建Voter
对象的方法:
Voter temp;
此外,您正在使用>>
运算符执行奇怪的操作。
为什么不简单:
int main()
{
vector<Voter> voterVector;
ifstream inFile("voters.txt");
if (!inFile) {
cout << "Unable to open voters.txt" << endl;
}
Voter temp;
while (inFile >> temp) {
voterVector.push_back(temp);
}
}