I am doing a c++ assignement regarding creating a calender and I\'m having some
ID: 3864224 • Letter: I
Question
I am doing a c++ assignement regarding creating a calender and I'm having some problem with my code. In my code I need the programmer to input two digits in day month and four in year. Example
If inputed 2/9/2005 the the date is considered invalid. Wrong format try again
If inputed 02/09/2005 the date is valid.
I cant figure out how to make this requriment in my code Here is my code for the input part :
void TheDate::input(){
cout<< "Enter a date (mm/dd/yyyy) or -1 to end: ";
cin>> month;
// if month was == -1 the program will exit
//if (month == -1)
//exit(1);
cin>> symbol;
cin>> day;
cin>> symbol;
cin >> year;
// call set method with above inputs day, month , year
set(day,month,year);
}
Explanation / Answer
In order to check for the validity of the date, we can firstread the date as a string and then check the no. of charatcters for that of the day, month and year, and simultaneously we can convert them and store them into integers.
Below is the code piece which should be used to for inputting the valid date.Please find the required code statements for your program
void TheDate::input(){
char date[10]; // to store the date in mm//dd/yyyy format i.e. it should be of length 10
int day=0,month=0,year=0,i=0; // to store the day, month and year in integer variables
cout<<"Enter date in mm/dd/yyyy format or -1 to end the program ";
cin>>date; // date is inputted by the user
if(date[0]=='-'&&date[1]=='1') // to check if -1 is entered
return 0; // to end the program
while(date[i]!='/'&&i<2){ // to check whether two-digit number is entered or not for month
month=month*10+int(date[i])-48; // conversion of string month characters to integer value. int y= int(c)-48 gives the value of the integer
i++;
}
if(i<2){ // if symbol appears before the two digits the the date is invalid
cout<<"Invalid date ";
return 0;
}
i++; // to skip the symbol
while(date[i]!='/'&&i<5){ // to check whether two-digit number is entered or not for day
day=day*10+int(date[i])-48; // conversion of string day characters to integer value. int y= int(c)-48 gives the value of the integer
i++;
}
if(i<5){ // if symbol appears before the two digits then the date is invalid
cout<<"Invalid date ";
return 0;
}
i++; // to skip the symbol
while(date[i]!=''&&i<10){ // to check whether four-digit number is entered or not for year
year=year*10+int(date[i])-48; // conversion of string year characters to integer value. int y= int(c)-48 gives the value of the integer
i++;
}
if(i<10){ // if symbol appears before the four digits then the date is invalid
cout<<"Invalid date ";
return 0;
}
// call set method with above inputs day, month , year
set(day,month,year);
} .
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.