Im having an extremely hard time finding a solution to this, I've looked on youtube and google but have not found a solution. With the followign code I have been unable to do the following:
1. Add information to a vector using the person datatype.
2. Creating a new element within the vector (pushback) once the information has been entered.
line 20 vector<person> p;
you're defining and empty vector, it equates to an empty array, you have to push back a member into the vector before you can call it.
You can never use p.firstname you have to specify which member of the vector you're referring to with []
#include <iostream>
#include <vector>
#include <string>
#include <vector>
usingnamespace std;
struct person
{
string firstname;
string lastname;
string email;
string id;
};
int main()
{
vector<person> p;
//hold temporary data to push back to p vector
person tempPerson;
cout << "First name: ";
cin >> tempPerson.firstname;
cout << "Last Name: ";
cin >> tempPerson.lastname;
cout << "Email: ";
cin >> tempPerson.email;
cout << "ID: ";
cin >> tempPerson.id;
p.push_back(tempPerson);
for (int i =0; i < p.size(); i++)
{
cout << "\n\nFirst name: " << p[i].firstname
<< "\nLast name: " << p[i].lastname
<< "\nEmail: " << p[i].email
<< "\nID: " << p[i].id;
}
}
Note that line 40 cout << p[i] << endl; p doesn't have an overloaded operator <<, so if you want you can either make a function to do so in the struct or like I did, display each of the variable one after the other.
Hope this helps
EDIT: also, line 38: for (int i =0; i < 5; i++), this is going to crash your program if your vector doesn't have at least 5 members, which in your case doesn't. You can use .size() for vectors to return the size of the vector, therefore not attempting to access data that isn't allocated