Why have you defined names
as a 2D array with 10
columns? Do you think you need to do this because you are going to create 10 objects of person
?
If that's the case, remember this: when you create the person
structure, you just have to define member variables for that one object.
So if your person
only has one name, and one sex (which needs 6 characters to define) just use that many because when you create 10 objects of person (person student[10];
) you are creating 10 unique copies of the person
object! So person[0].name
is different from person[1].name
.
So let's first define member variables in person
for one person:
struct person
{
char names[20];
char sex[6];
int age;
int month;
int day;
int year;
};
And then assign characters to the name as you've detailed in your code.
Now, this is not a great idea because names
is uninitialized. So student[0].names[4]
is undefined (when it should a null character to terminate it). Have you considered using std::string
? You have C++ after all!
Also, you'll notice I've changed the definition of person
('struct person ... instead of
typedef .. `) since this is all you need to do in C++.
Changes:
Consider the following person
structure:
#include <string>
struct person
{
std::string person;
std::string sex;
int age;
int month;
int day;
int year;
};
Now, you can assign a string by just:
person student[10];
student[0].name = "Cami";
student[0].sex = "Female";
student[0].age = 16;
student[0].month = 8;
student[0].day = 2;
student[0].year = 1993;
And suppose you want to populate it with a for
loop with keyboard input --- it's much easier now:
#include <iostream>
for(int i = 0; i < 10; ++i)
{
std::cin>>student[i].name;
std::cin>>student[i].sex;
std::cin>>student[i].age;
std::cin>>student[i].month;
std::cin>>student[i].day;
std::cin>>student[i].year;
}