我创建了一个名为" Person"它有一个名字,三套高分和一个图片链接。我正在从包含所有这些变量的文本文件中读取并创建几个" Person"相应的对象,然后将它们放入" Person"对象。
这是一个接收空向量并输出添加了人物的向量的函数。
void input_data(vector<Person>& input){
ifstream ifs("personData.txt");
while (true) {
if (ifs.eof()) {
return;
}
Person n;
string name;
string picture;
string check;
int t1;int t2;int t3;
int r1;int r2;int r3;
int f1;int f2;int f3;
getline(ifs,name); // use getline to deal with spaces
getline(ifs,picture); // use getline to deal with spaces
ifs >> t1 >> t2 >> t3;
ifs >> r1 >> r2 >> r3;
ifs >> f1 >> f2 >> f3;
ifs.ignore(100, '\n');
getline(ifs,check); // use getline to deal with spaces
n.setName(name);
n.setPic(picture);
n.addScore(3, t1);n.addScore(3, t2);n.addScore(3, t3);
n.addScore(4, r1);n.addScore(4, r2);n.addScore(4, r3);
n.addScore(5, f1);n.addScore(5, f2);n.addScore(5, f3);
input.push_back(n);
if(check == ""){
cout << endl << "breaking" << endl;
break;
}
}
}
如您所见,使用&#34; addScore&#34;函数,我打算根据输入的类型(3,4或5)改变每个人的分数矢量。这是使用的Person类。将值添加到向量的逻辑用于在每个向量中保持3的大小,因此我将新值添加到向量,对其进行排序,然后删除最小的条目。这给了我三个高分。
class Person{
private:
//basic member functions
string name;
string pic;
vector<int> highThree;
vector<int> highFour;
vector<int> highFive;
public:
//constructor jsut makes eveything zero
Person(string m_name = "", string m_pic = ""):
name(m_name),
pic(m_name),
//initializing every vector to three instnace of 0
highThree(3,0),
highFour(3,0),
highFive(3,0){}
//manipulating member functionsjj
void setName(string i_name){name = i_name;}
string getName(){return name;}
void setPic(string i_pic){pic = i_pic;}
string getPic(){return pic;}
//logic for adding to the highschores
void addScore(int gameType, int val){
//(which is sorted), then add it and sort it again
if (gameType == 3){
//name = "yo";
highThree.push_back(val);
//sort the vector
sort(highThree.begin(), highThree.end());
//erase the first thing
highThree.erase(highThree.begin());
}
if (gameType == 4){
highFour.push_back(val);
sort(highFour.begin(), highFour.end());
highFour.erase(highThree.begin());
//cout << val << endl;
}
if (gameType == 5){
highFive.push_back(val);
sort(highFive.begin(), highFive.end());
highFive.erase(highThree.begin());
//cout << val << endl;
}
}
//gets the three score vecotors
vector<int>& getScores(int gameType){
if (gameType == 3){
for(int i = 0; i<highThree.size(); i++){
cout << highThree[i] << endl;
}
return highThree;
}else if(gameType == 4){
return highFour;
}else if(gameType == 5){
return highFive;
}else{
cout << "error in getScores input\n";
vector<int> bad;
return bad;
}
}
};
主要是,当我尝试访问其中一个成员向量中的分数时,我得到的结果与我从文件中获取的结果不准确。实际上,我在&#34; addScore&#34;中打印了输入值。功能以及&#34; input_data&#34;功能,他们是正确的。这意味着我准确地从文件中获取数据,但是后面的内容有问题。
int main(){
vector<Person> peeps;
input_data(peeps);
//the value that i get below is wrong
cout << peeps[0].getScores(3)[0];
}
我在上面打印中得到的值是0,当它应该是8 。我正在阅读的文本文件附在下面。我为这么长的帖子道歉,但我已经和我的所有队友谈过这个问题,似乎无法弄清楚出了什么问题。检索成员向量的内容似乎存在问题,但我找不到问题。
bob
mypic
8 9 10
3 4 5
2 7 6