我正在从文件中读取我的结构,我想将它们添加到结构的向量中.以下是它的外观和工作原理:
typedef struct
{
int ID;
string name;
string surname;
int points;
}
Student;
int main()
{
ifstream theFile("test.txt");
std::vector<Student*> students;
Student* s = new Student();
while(theFile >> s->ID >> s->name >> s->surname >> s->points)
{
studenti.push_back(s); // here I would like to add this struct s from a file
}
// here I want to print each struct's values on the screen, but the output is always ONLY last struct N times, and not all of them, each only once
std::vector<Student*>::const_iterator it;
for(it = students.begin(); it != students.end(); it+=1)
{
std::cout << (*it)->ID <<" " << (*it)->name << " " << (*it)->surname <<" " << (*it)->points <<endl;
}
Run Code Online (Sandbox Code Playgroud)
我应该怎么做才能将我的结构添加到矢量中,并将它们正常打印出来(如果结构正确加载到矢量中,这个打印真的只是一个检查)?
你的错误是使用指针
std::vector<Student> students;
Student s;
while(theFile >> s.ID >> s.name >> s.surname >> s.points)
{
students.push_back(s);
}
Run Code Online (Sandbox Code Playgroud)
现在它会起作用.
问题是你一遍又一遍地重复使用相同的指针.所以你最终会得到一个指向同一个对象的指针向量.哪个将有最后一个学生读入的值.
当更简单的一个是正确的时候,选择复杂的替代方案似乎是一个相当普遍的初学者特征,所以我很想知道为什么你选择使用指针.
以下是现代C++中代码的外观:
#include <string>
#include <istream>
#include <vector>
struct Student
{
int ID;
std::string name;
std::string surname;
int points;
Student(int i, std::string n, std::string s, int p)
: ID(i), name(std::move(n)), surname(std::move(s)), points(p) {}
};
std::vector<Student> read_students(std::istream & is)
{
std::vector<Student> result;
std::string name, surname;
int id, points;
while (is >> id >> name >> surname >> points)
{
result.emplace_back(id, name, surname, points);
}
return result;
}
Run Code Online (Sandbox Code Playgroud)
用法:
#include <fstream>
#include <iostream>
int main()
{
std::ifstream infile("test.txt");
auto students = read_students(infile);
// ...
}
Run Code Online (Sandbox Code Playgroud)