Reputation: 1
I would like the function dateCreate to pass the given parameters to the ones from the struct.
I have tried by having the Date d variable as a function parameter but it still shows me the error "field "day/month/year" could not be resolved".
struct Date{
int day;
int month;
int year;
} ;
Date dateCreate (int d, int m, int y){
Date d;
d.day =d;
d.month = m;
d.year =y;
return 0;
};
int main() {
int d,m,y;
cin << d << m << y;
cout << dateCreate(d,m,y); //Not completely sure if this is right either.
return 0;
}
I want the function to create a Date type of data from the integers given. Thank you very much.
Upvotes: 0
Views: 84
Reputation: 27365
Equivalent code:
struct Date
{
int d;
int m;
int y;
};
int main()
{
int d = 1, m = 1, y = 1980;
std::cin >> d >> m >> y;
Date date{d, m, y}; // default constructor is called here
}
This said, because the problem you are solving is reading a date, you should probably implement it like this:
struct Date
{
int d;
int m;
int y;
};
std::istream& operator >>(std::istream& in, Date& d)
{
int d = 1, m = 1, y = 1980;
if(in >> d >> m >> y) // only set values if they were read successfully
d = Date{d, m, y};
return in;
}
Client code:
int main()
{
Date d{1, 1, 1980};
in >> d;
}
Upvotes: 1
Reputation: 38267
The most concise way to fix your snippet is providing an output operator for Date
objects, e.g.
std::ostream& operator << (std::ostream& os, const Date& date)
{
return os << date.day << "/" << date.month << "/" << date.year;
}
then using the correct operators to read the user input
cin >> d >> m >> y;
and finally using the Date
constructor generated by the compiler:
cout << Date{d, m, y};
You don't need a function creating a date object as long as you don't verify the input.
Note, however, that Date
objects can now be in invalid states (negative day or month values etc.), so for future refinement, you should either implement a proper constructor that throws upon illegal input, or change the createDate
function such that it e.g. returns a std::optional<Date>
which is empty (std::nullopt
) upon illegal input.
Upvotes: 0
Reputation: 117856
Rather than a free function, I'd suggest you give your struct
a constructor
struct Date{
Date(int _day, int _month, int _year)
: day(_day), month(_month), year(_year)
{ }
int day;
int month;
int year;
};
Then you can create this object like
int d,m,y;
cin >> d >> m >> y;
Date date(d, m, y);
To do something like
cout << date;
you'd need to overload operator<<
for your Date
struct
Upvotes: 1
Reputation: 136208
dateCreate
should return d
, not 0
.
For expression cout << dateCreate(d,m,y)
to compile you need to implement std::ostream& operator<<(std::ostream&, Date const&)
.
Upvotes: 2