Problem using vector

Im working on this program which is supposed to let you write in som players and then print them out on the screen but the problem is I can't seem to figure out where im going wrong, I managed to make a working program by using various vectors in my class but I wanted to do it with just one but I keep getting errors :(

Can someone please enlighten me!


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
/PlayerDetails.cpp
#include<iostream>
#include<string>
#include<vector>

using namespace std;

class Player {
    public:
    void setPlayer (string name, int age);
    void getPlayer();
    private:
    string name;
    int age;
};

void Player::setPlayer(string name, int age)
{
    vector<Player>Pvec;
    Player p;

    cout << "Name: ";
    getline(cin, p.name);
    Pvec.push_back(p.name);
    cout << "Age:  ";
    cin >> p.age;
    Pvec.push_back(p.age);
    cout << endl;
};

void Player::getPlayer()
{
    for (vector<Player>::iterator it = Pvec.begin(); it != Pvec.end(); ++it)
    {
        cout << *it << endl;
    }
};

int main()
{
    Player pp;
    string nn;
    int aa, choice;

    do
    {
        cout << "(1) add player (2) show players (0) quit ";
        cin >> choice;
        if (choice == 1)
        {
            pp.setPlayer(nn, aa);
        }
        else if (choice == 2)
        {
            pp.getPlayer();
        }
    } while (choice != 0);
}
You should make the vector part of your class.
Last edited on
You might consider creating a class called Players, where vector<Player>Pvec is a member of that class. In other words, Players contains a vector of player objects. player could just be a nested struct or class type within Players, containing the data that makes up a players.

In your program, getPlayer is trying to access Pvec which was created and destroyed within the setPlayer function.
Topic archived. No new replies allowed.