Greeting,
I wonder how can I improve my validity check for user input? I only want them to key in certain range of digit.
Also for my validity check, when I key in character such as ABC, it lead to infinity loop
Here is my code :
Code:
/*Write a program that can calculate user's age by getting user input their birth date.*/
#include "stdafx.h"
#include <iostream>
#include <time.h>
using namespace std;
int main()
{
int yyyy, mm, dd; //year, month, day
int i = 0; //for the sake of validity check
// current date/time based on current system
time_t t = time(0);
tm *now = localtime(&t);
/* Find a better way to validate user input
* "isDigit" should able to do the trick
* Bug : Key in character lead to infinity loop
*/
//Year
do
{
cout << "Enter your birth date of Year:\n?";
cin >> yyyy; //do checking
if (yyyy > 1900 && yyyy < 2500) { //2500..? Lol
i++; //i=1
}
} while(i == 0);
//Month
do
{
cout << "Enter your birth date of Month:\n?";
cin >> mm; //do checking
if (mm > 0 && mm < 13) { // 1 ~ 12
i++; //i=2
}
} while(i == 1);
//Day
do
{
cout << "Enter your birth date of Date:\n?";
cin >> dd; //do checking
if (dd > 0 && dd < 32) { //I'm kind of lazy to check how many days in a month, well, 1 ~ 31
i++; //i=3
}
} while(i == 2);
/*End of user input*/
//Think a way to improve this so those comment will not needed
if (mm <= (now->tm_mon + 1)) { //if birthday month <= current month
if (dd <= (now->tm_mday)) { //if birthday date <= current date
cout << "Your age is: " << (1900 + now->tm_year) - yyyy << "years,"; //Already pass birthday
cout << " " << ((now->tm_mon + 1) - mm) << "months,"; //1 has added into years
cout << " and " << ((now->tm_mday) - dd) << "days" << endl; //and so the day
} else {
cout << "Your age is : " << (1900 + now->tm_year) - yyyy - 1 << "years,"; //Not yet pass birthday
cout << " " << ((now->tm_mon + 1)) << "months,"; //just print how many months
cout << " and " << ((now->tm_mday)) << "days" << endl; //and day you lived
}
} else {
cout << "Your age is : " << (1900 + now->tm_year) - yyyy - 1 << "years,"; //Not yet pass birthday
cout << " " << ((now->tm_mon + 1)) << "months,"; //just print how many months
cout << " and " << ((now->tm_mday)) << "days" << endl; //and day you lived
}
}
Regards,
Milo.