critique my code please
im currently trying to get the hang of passing/returning structures to and from fuctions and also passing structure addresses.
am doing it right, guys?
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 59 60 61
|
#include <iostream>
using std::string;
struct person_struc
{
string name;
short age;
};
void displayPerson(const person_struc *p);
person_struc getPerson(short a, string na);
int main()
{
short bge = 0;
string Name;
const int MAX = 3;
person_struc* X = new person_struc [MAX]; // dynamically allocate a person_struct array the size of 3 (for three "people")
for (int x = 0; x < MAX; x++)
{
/////////input//////////
std::cout << "enter name: ";
std::getline(std::cin, Name);
std::cout << "enter age: ";
std::cin >> bge;
//////////////////////
std::cin.clear();/////////////////
std::cin.ignore();// clear and "reset" cin for input values bge and Name
X[x] = getPerson(bge, Name); /////// fill person_struct array with the Name and bge input values
}
std::cout << "\n\n";
for (int y = 0; y < MAX; y++) //display person_struct array
{
displayPerson(&X[y]); //pass the address of the X array element ( y ) to displayPerson
std::cout << "\n";
}
delete [] X; //delete person_struct array
return 0;
}
void displayPerson(const person_struc *p)
{
if ((p->name == "bob") && (p->age == 17))
{
std::cout << "i knew a " << p->name << " who was once " << p->age << "\n";
}
else
{
std::cout << "name |\t" << p->name << "\n";
std::cout << "age |\t" << p->age << "\n";
}
}
person_struc getPerson(short a, string na)
{
person_struc S;
S.name = na;
S.age = a;
return S;
}
| |
It's Ok.
I would get rid of the
getPerson
method and change
X[x] = getPerson(bge, Name);
to
1 2
|
X[x].name = Name
X[x].age = bge;
| |
Cuts down on extra assignments and structure copies.
Also, another way to write
displayPerson(&X[y]);
is
displayPerson( X+y );
Topic archived. No new replies allowed.