In: Computer Science
Written in C++. I need to create function printShort exactly like this description: "printShort ( ) - prints the Date in the format m/d/yy (no leading zeros for month and day, and two last digits for year with leading zeros (use fill digit ‘0’) if necessary). Use the accessors to get the values of the data members. " Right now it is showing the correct output for month and day, but still printing a 4 digit year. How would I only print the last two digits of the variable year? For example, with March 31, 2020 the year's value is set to '2020', but it should be written 3/31/20
Function code:
void Date::printShort(){
cout<<getMonth()<<"/";
cout<<getDay()<<"/";
cout<<setfill('0')<<setw(2)<<getYear();
}//end printShort
For this, I suggest you to use %, i.e., modulo operator, which is an arithmatic operator in C++.
The modulo division operator produces the remainder of an integer division.
Syntax: If x and y are integers, then the expression:
x % y
produces the remainder when x is divided by y.
Return Value:
Example:- (i) 2020 % 100 will give us 20 as result, i.e., the last two digits of the number
(ii) 252 % 10 will give us 2 as result, i.e., the last digit of the number.
Modified function definition:-
void Date::printShort(){
cout<<getMonth()<<"/";
cout<<getDay()<<"/";
cout<<setfill('0')<<setw(2)<<(getYear()%100);
}//end printShort
Explanation:- We are using modulo operator for the value returned by getYear() method divided by 100. This will give us the last two digits of the year.
I have also test this on some given input-output, assuming function definitions on my own.
You can check my assumed code below here:-
Output for the same is:-
Thank you.
Happy Learning...