Reputation: 23
i have a problem.
struct Info{
string name;
string lastname;
int BirthDate[];
int DeathDate[];
}human[2];
......
for(int j=0; j < 3; j++){
ReadFromFile >> human[0].BirthDate[j];
}
......
When i run this, my compiler stops working. But if i change
for(int j=0; j < 3; j++){
ReadFromFile >> human[0].BirthDate[j];
}
To:
for(int j=0; j < 3; j++){
ReadFromFile >> human.BirthDate[j]; //Removing array from struct too
}
Everything works fine. So my question is it possible somehow to do it with array's? For example i have 2 humans, and i want to read their BirthDate's from file. I can't make 2 variables becouse at first i don't know how much humans i'll have in my file.
Upvotes: 1
Views: 749
Reputation: 11
The first problem is that you try to create an array without size:
int BirthDate[];
int DeathDate[];
https://learn.microsoft.com/en-us/cpp/cpp/arrays-cpp?view=msvc-170&viewFallbackFrom=vs-2019
https://cplusplus.com/forum/beginner/7961/
your options are to change it to something like this:
#define DATE_SIZE 3
int BirthDate[DATE_SIZE];
int DeathDate[DATE_SIZE];
and the loop will be:
for (int i=0; i < 2; ++i){
for(int j=0; j < DATE_SIZE; j++){
ReadFromFile >> human[i].BirthDate[j];
}
}
or change it to struct/class, like this:
struct date {
int day;
int month;
int year;
}
and the struct be:
struct Info{
string name;
string lastname;
date BirthDate;
date DeathDate;
} human[2];
the loop:
for (int i=0; i < 2; ++i){
ReadFromFile >> human[i].BirthDate.day;
ReadFromFile >> human[i].BirthDate.month;
ReadFromFile >> human[i].BirthDate.year;
}
Upvotes: 0
Reputation: 11406
No need for array's for BirthDate
and DeathDate
?
Also: your j
counts to 3.
Try this:
struct Info{
string name;
string lastname;
int BirthDate;
int DeathDate;
} human[2];
......
for(int j=0; j < 2; j++){
ReadFromFile >> human[j].BirthDate;
}
......
Update:
BirthDate contains like this: 2015 12 28 in file.
As Thomas Matthews says:
struct MyDate {
unsigned int year;
unsigned int month;
unsigned int day;
};
struct Info{
string name;
string lastname;
MyDate BirthDate;
MyDate DeathDate;
} human[2];
......
ReadFromFile >> human[0].BirthDate.year;
ReadFromFile >> human[0].BirthDate.month;
ReadFromFile >> human[0].BirthDate.day;
......
Upvotes: 3
Reputation: 169
Do something like this:
struct Date{
int day;
int month;
int year;
};
struct Info{
string name;
string lastname;
Date BirthDate;
Date DeathDate;
}human[2];
ReadFromFile >> human[0].BirthDate.day;
ReadFromFile >> human[0].BirthDate.month;
Upvotes: 2