Questions about this code?

closed account (LN3RX9L8)
In the function printPlayer why do we have to use p.print whenever we output to the screen?? Can someone explain how struct works and strings thanks!

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
 
#include <iostream>
#include <string>
using namespace std;

struct FootballPlayer
{
    string name;
    int number;
    string team;
    double salary;
    string eyes; 
};

void printPlayer(FootballPlayer p);

int main()
{
    FootballPlayer AR;
    
    AR.name = "Manti Te'o";
    AR.number = 5;
    AR.team = "Notre Dame University";
    AR.salary = 8000000;
    AR.eyes= "brown";
    
    printPlayer(AR);
    
}

void printPlayer(FootballPlayer p)
{
    cout.setf(ios::showpoint);
    cout.setf(ios::fixed);
    cout.precision(2);
    
    cout << p.name << " is number #" << p.number << " and plays for " << p.team << endl;
    cout << "His annual salary is $" << p.salary << endl;
    cout<<"He has " <<p.eyes << " eyes"<< endl; 
}
You have to use p.x because it's not a method that is part of the struct so it has to specifically reference the elements of the object.

Have a read through: http://www.cplusplus.com/doc/tutorial/
You have to create an object of the structure FootballPlayer, which you did and labeled it p. So when you want to access the variables inside of the structure, you'd write p.x where x is the name of the variable, so the computer knows to look for the x value inside of the structure.
Topic archived. No new replies allowed.