我是 C++ 的新手。我正面臨一個問題。我想要 2 個不同的日期 (DD/MM/YYYY) 如何為第一個塊分配一個整體變量,為第二個塊分配另一個變量?
例如:
First Day of date: 2
First Month "" : 5
First year "" : 1985
-------
Second ""
second ""
second ""
--------
如果兩者是相同的日期,則輸出將是“兩者都相等”,否則將提到更大的“日期......更大”
我提前感謝您的幫助。
#include <iostream>
using namespace std;
int main()
{
//This should be my first chunk
int first_date;
cout << "first day: ";
cin >> first_y;
int first_month;
cout << "first month: ";
cin >> first_month;
int first_year;
cout << "first year: ";
cin >> first_year;
}
在下面的方案顯示你想要什麼:
#include <iostream>
struct Date
{
//always always initialize built in type in block/local scope
int date = 0, month = 0, year = 0; // by default public
//default constructor
Date() = default;
//lets overload operator= for comparing two Date types as you desire
friend bool operator==(const Date &lhs, const Date &rhs);
friend bool operator!=(const Date &lhs, const Date &rhs);
//overload operator>> for taking input from user
friend std::istream& operator>>(std::istream &is, Date &rhs);
};
bool operator==(const Date &lhs, const Date &rhs)
{
return lhs.date == rhs.date &&
lhs.month == rhs.month &&
lhs.year == rhs.year;
}
bool operator!=(const Date &lhs, const Date &rhs)
{
return !(lhs == rhs);
}
std::istream& operator>>(std::istream &is, Date &rhs)
{
std::cout<<"Enter date: ";
//take date as input from user
std::cin >> rhs.date;
std::cout<<"Enter month: ";
//take month as input from user
std::cin >> rhs.month;
std::cout<<"Enter year: ";
//take year as input from user
std::cin >> rhs.year;
//check if input succedded
if(!is)
{
rhs = Date();
}
return is;
}
int main()
{
//create first Date
struct Date d1;
std::cin >> d1;//take input from user
//create second Date
struct Date d2;
std::cin >> d2;//take input from user
//lets check if dates d1 and d2 entered by user are equal or not
std::cout<<"The dates d1 and d2 are: "<<(d1==d2? "equal": "not equal")<<std::endl;
return 0;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句