【发布时间】:2015-07-16 20:14:16
【问题描述】:
我有一些 C++ 代码:
#include <bjarne/std_lib_facilities.h>
struct Date {
int month;
int day;
int year;
};
Date get_date();
Date get_birth_date();
int days_in_month (int month);
bool is_valid_date (const Date& date);
bool is_before (const Date& date1, const Date& date2);
int main()
{
cout << "Welcome to Age Calculator!\n";
Date current;
current = get_date();
cout << "Would you like to see how old you are (y/n)?";
char answer, slash;
cin >> answer;
Date birthday;
if(answer == 'y'){
birthday = get_birth_date();
bool valid = is_valid_date (birthday);
bool before = is_before (current,birthday);
while(!valid && !before){
cout << "Invalid birth date? Please re-enter: ";
cin >> birthday.month >> slash >> birthday.day >> slash >> birthday.year;
valid = is_valid_date (birthday);
before = is_before (current,birthday);
}
cout << "Your birthday is: " << birthday.month << "/" << birthday.day << "/" << birthday.year << "\n";
}
else
cout << "You are so chicken! \n";
}
Date get_date()
{
cout << "Please enter today's date (mm/dd/yyyy): ";
Date today;
char slash;
cin >> today.month >> slash >> today.day >> slash >> today.year;
bool valid = is_valid_date (today);
while(!valid){
cout << "Invalid date? Please re-enter: ";
cin >> today.month >> slash >> today.day >> slash >> today.year;
valid = is_valid_date (today);
}
cout << "Date entered was: " << today.month << "/" << today.day << "/" << today.year << "\n";
return today;
}
Date get_birth_date()
{
cout << "Please enter your birth date (mm/dd/yyyy): ";
Date birth;
char slash;
cin >> birth.month >> slash >> birth.day >> slash >> birth.year;
return birth;
}
int days_in_month (int month)
{
int month31[7] = {1,3,5,7,8,10,12};
for(int i = 0; i < 7; i++){
if(month == month31[i])
return 31;
}
int month30[4] = {4,6,9,11};
for(int i = 0; i < 4; i++){
if(month == month30[i])
return 30;
}
if(month == 2)
return 28;
}
bool is_valid_date (const Date& date)
{
int months[12] = {1,2,3,4,5,6,7,8,9,10,11,12};
int days = 0;
for(int i = 0; i < 12; i++){
if(date.month == months[i]){
days = days_in_month (date.month);
if(date.day <= days && date.day > 1){
return true;
}
}
return false;
}
bool is_before (const Date& date1, const Date& date2)
{
cout << date1.day << " " << date2.day;
if(date2.year < date1.year){
return true;
}
else if(date2.year == date1.year)
{
cout << "-";
if(date2.month < date1.month)
return true;
else if(date2.month == date1.month){
if(date2.day <= date1.day)
return true;
}
else
return false;
}
return false;
}
我知道 is_valid_date 函数有效,但是当我测试输入当天之后的生日时,由于某种原因,它通过了 is_before 测试并且永远不会进入 while 循环要求用户输入有效的生日。任何建议将不胜感激!提前致谢!
编辑:我正在测试的具体输入是:对于今天的日期,我输入 05/06/2015,对于生日,我输入 05/07/2015。然后它会打印生日,这意味着它会跳过 int main() 中的 while 循环,它不应该这样做,因为生日在当前日期之后。
【问题讨论】:
-
您可能希望在发布问题之前清理一些调试代码。有些人可能会觉得这很有趣,但其他人可能会被冒犯:)
-
是的,去掉脏话,否则你会被否决和/或你的问题被关闭:/
-
啊,是啊,我真的很抱歉我忘了把它拿出来!感谢您的编辑
-
如果您发布了代码失败的特定输入,这也会有所帮助。例如,您输入的今天的日期和出生日期会导致意外行为。
-
您为
is_valid_date发布的代码缺少结束}。这是抄写的错误吗?
标签: c++ struct while-loop boolean