I'm having quite a bit of trouble on this program. I have quite a few logic errors that I'm not quite able to iron out.
The program should be able to:
Collect 10 names and ages using an array of objects.
Calculate the average of the ages.
Print the names and ages as well as the person's difference from the average age.
The problem is when trying to input it will keep outputting the prompts after the first try without giving the user a chance to enter in more information.
Also when printing, it keeps outputting garbage instead of what was input.
I know it's a lot but i could really use some help, im sort of having a brain block as for what to do.
totalAge in the class shouldn't be there or even being used - totalAge can only be seen by its own object as detailed above in a previous post which is why I suggested a getter function to retrieve the age from the object and total it up externally in the main() function.
If you are still getting garbage, post your code so I can see what you have now - I just quickly tested the code with the modifications here and it worked fine.
I think I know what you mean when you refer to garbage - I am guessing you are still trying to run lines 32-34 - remember each object would have its own totalAge, calculations such as this need to be done in the main function so you can access each objects age.
#include <iostream>
usingnamespace std;
class Data{
private:
int age;
char name[31];
public:
void storeData();
void printData();
int getAge();
};
int Data::getAge()
{
return age;
}
void Data::storeData()
{
cout << "Please enter a name (Max: 30 characters)." << endl;
cin.getline(name, 30);
cout << "Please enter an age." << endl;
cin >> age;
}
void Data::printData(){
cout << "Name: " << name;
cout << " Age is: " << age;
}
void main()
{
Data get[10];
int totalAge = 0;
int average = 0;
// read in the data
for (int i = 0; i < 10; i++)
get[i].storeData();
// print out the data
for (int i = 0; i < 10; i++) {
get[i].printData();
totalAge += get[i].getAge();
}
// show statistics
average = totalAge / 10;
cout << endl << "Total of all ages: " << totalAge << endl;
cout << "Average is: " << average << endl;
}