#include<iostream>
using namespace std;
class Date {
int Day;
int Month;
int Year;
public:
void setDay(int day) {
if(day>=1 && day<=31)
Day = day;
}
int getDay() {
return Day;
}
void setMonth(int month) {
if(month <= 12)
Month = month;
}
int getMonth() {
return Month;
}
void setYear(int year) {
if(year >=1111)
Year = year;
}
int getYear() {
return Year;
}
void DisplayDate()
{
cout << "Days: " << Day << " \n";
cout << "Month: " << Month << " \n";
cout << "Year: " << Year << " \n";
}
Date(int day, int month, int year) {
Day = day;
Month = month;
Year = year;
}
void Birthday()
{
cout << "Your Birthday is " << Day << " / " << Month << " / " << Year << "\n";
}
};
int main()
{
Date date1 = Date(10, 10, 2000);
date1.DisplayDate();
date1.Birthday();
}
This code is enter date year and month .
how do i add the cin function to ask the user to enter his data.
i have tried adding Cin in my main function but it provides me with lots of errors
..............................................................................
................................................................................
..........................................................................
................................................................................
CodePudding user response:
Don't know what problem it is you are having, could you list the errors you are getting? You should be able to just write 'int day; cin >> day;'.
CodePudding user response:
Im assuming you did something like
cin >> date1.Day >> date2.Month >> date3.Year
, which obviously won't work since your variables are private. Make them public or enter them in other variables and set their values by using a method.
CodePudding user response:
You can simply write a constructor which gets the data you need from any std::istream
object like std::cin
.
Simply add the constructor to your class:
class Date {
int Day;
int Month;
int Year;
public:
Date( std::istream& is )
{
std::cout << "Please enter day" << std::endl;
is >> Day;
std::cout << "Please enter Month" << std::endl;
is >> Month;
std::cout << "Please enter Year" << std::endl;
is >> Year;
}
... REST OF YOUR CLASS ...
};
int main()
{
//Date date1 = Date(10, 10, 2000);
// Construct your object with the constructor and the `std::cin` object
Date date1{ std::cin };
date1.DisplayDate();
date1.Birthday();
}
Now you can also constrcut your class from a file or any other std::istream
. If you like o also read from files, it makes no sense to output to std::cout
for the requested parms :-)
CodePudding user response:
Cannot understand what is your problem,add the cin function to ask the user to enter his data,like this?
{
int day, month, year;
cout << "plearse enter day month year" << endl;
cin >> day >> month >> year;
Date date1 = Date(day, month, year);
date1.DisplayDate();
date1.Birthday();
}