This is a c leap year calculator I worked so far But I could
This is a c++ leap year calculator I worked so far.
But I couldn\'t seem to figure out whether how to skip day cin if the user pressed enter, but still keep the input checker if the user inputs.
hope someone could help me out with this! Thank you!
#include <iostream>
#include <string>
using namespace std;
int days_in_month[] = { 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
int day, month, year;
bool isLeapYear(int);
void printResualt();
int main(int argc, char *argv[]) {
cout << \"Please input a year:\";
cin >> year;
while(year<=0)
{
cerr<<\"Please input a valid year thats larger than 0:\";
cin >> year;
}
cout << \"Please input a month:\";
cin >> month;
while(month <1||month>12)
{cerr << \"Please input a valid month that is (1 ~ 12):\";
cin >> month;}
cout << \"Please input a day:\";
cin<< day;
cin.ignore();
while(day <1||day>31)
{cerr << \"Please input a valid day that is (1 ~ 31):\";
cin >> day;}
while (day> days_in_month[month])
{
cerr<<\"Month \"<<month<< \" doesnt have \"<< day << \" days!\"<<endl;
cerr<<\"Please re-enter: \";
cin>>day;
}
printResualt();
}
void printResualt(){
if(isLeapYear(year))
{
cout<< \"Yes! it is a leap year.\";
}
else
{
cout<< \"Nope, it is not a leap year.\";
}
}
bool isLeapYear( int year )
{
return ((year % 4 == 0 && year % 100 != 0) || ( year % 400 == 0)||(day==29));
}
Solution
Hi,
I have fixed the issue. Highlighted the code changes below.
Issue is with below statement
cin<< day;
This statement should be like this cin>> day;
#include <iostream>
#include <string>
using namespace std;
int days_in_month[] = { 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
int day, month, year;
bool isLeapYear(int);
void printResualt();
int main(int argc, char *argv[]) {
cout << \"Please input a year:\";
cin >> year;
while(year<=0)
{
cerr<<\"Please input a valid year thats larger than 0:\";
cin >> year;
}
cout << \"Please input a month:\";
cin >> month;
while(month <1||month>12)
{cerr << \"Please input a valid month that is (1 ~ 12):\";
cin >> month;}
cout << \"Please input a day:\";
cin>> day;
cin.ignore();
while(day <1||day>31)
{cerr << \"Please input a valid day that is (1 ~ 31):\";
cin >> day;}
while (day> days_in_month[month])
{
cerr<<\"Month \"<<month<< \" doesnt have \"<< day << \" days!\"<<endl;
cerr<<\"Please re-enter: \";
cin>>day;
}
printResualt();
}
void printResualt(){
if(isLeapYear(year))
{
cout<< \"Yes! it is a leap year.\";
}
else
{
cout<< \"Nope, it is not a leap year.\";
}
}
bool isLeapYear( int year )
{
return ((year % 4 == 0 && year % 100 != 0) || ( year % 400 == 0)||(day==29));
}
Output:
sh-4.3$ g++ -std=c++11 -o main *.cpp
sh-4.3$ main
Please input a year:2000
Please input a month:2
Please input a day:29
Month 2 doesnt have 29 days!
Please re-enter: 2008
Month 2 doesnt have 2008 days!
Please re-enter: 28
Yes it is a leap year



