Vector of structs: adding elements C++
46,120
Solution 1
Here's how the code might look in modern 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;
}
Usage:
#include <fstream>
#include <iostream>
int main()
{
std::ifstream infile("test.txt");
auto students = read_students(infile);
// ...
}
Solution 2
Your mistake is to use pointers
std::vector<Student> students;
Student s;
while(theFile >> s.ID >> s.name >> s.surname >> s.points)
{
students.push_back(s);
}
Now it will work.
The problem was that you were reusing the same pointer over and over. So you end up with a vector of pointers all pointing at the same object. Which will have values for the last student read in.
It seems a fairly common beginner trait to choose the complex alternative when the simpler one is correct so I would be interested to know why you chose to use pointers.
Author by
Whizzil
Updated on March 01, 2020Comments
-
Whizzil about 4 years
I am reading my structs from a file, and I would like to add them to vector of structs. Here is how it looks and works:
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; }
What should I do so I can add my structs to a vector, and print them out normally (this print is only a check really, if the structs are properly loaded into vector)?