Jan 29, 2013 at 3:44pm UTC
After running the following program but have a couple of question's:
1. The first line in main is: Person people[128] does this allocate space for
128 entries in class Person?
2. The first fuction has the line Person person.
I presume the first Person refers to the class Person, Does the second
person give a name to the array?
#include <iostream>
#include <cstdlib>
#include <cstdio>
class Person
{
public:
char szFirstName[128];
char szLastName[128];
int nSocialSecurityNumber;
};
Person getPerson()
{
Person person;
std::cout << "\nEnter another person\n" << "First name: ";
std::cin >> person.szFirstName;
std::cout << "Last name: ";
std::cin >> person.szLastName;
std::cout << "Social Security number: ";
std:: cin >> person.nSocialSecurityNumber;
return person;
}
int getPeople(Person people[], int nMaxSize)
{
int index;
for(index = 0; index < nMaxSize; index++)
{
char cAnswer;
std::cout << "Enter another name? (Y or N)";
std::cin >> cAnswer;
if (cAnswer != 'Y' && cAnswer != 'y')
{
break;
}
people[index] = getPerson();
}
return index;
}
void displayPerson(Person person)
{
std::cout << "First name: " << person.szFirstName << std::endl;
std::cout << "Last name : " << person.szLastName << std::endl;
std::cout << "Social Security number : " << person.nSocialSecurityNumber << std::endl;
}
void displayPeople(Person people[], int nCount)
{
for(int index = 0; index < nCount; index++)
{
displayPerson(people[index]);
}
}
void sortPeople(Person people[], int nCount)
{
int nSwaps = 1;
while(nSwaps != 0)
{
nSwaps = 0;
for(int n = 0; n < (nCount - 1); n++)
{
if (people[n].nSocialSecurityNumber > people[n + 1].nSocialSecurityNumber)
{
Person temp = people[n + 1];
people[n + 1] = people[n];
people[n] = temp;
nSwaps++;
}
}
}
}
int main(int nNumberofArgs, char* pszArgs[])
{
Person people[128];
std::cout << "Read name/social security information\n";
int nCount = getPeople(people, 128);
sortPeople(people, nCount);
std::cout << "\nHere is the list sorted by " << "social security number" << std::endl;
displayPeople(people, nCount);
return 0;
}
Jan 29, 2013 at 4:09pm UTC
1) Yes.
2) It declares a variable named person of type Person
Jan 29, 2013 at 6:38pm UTC
1) Not space for 128 entries in class Person, but space for 128 instances of class Person.