Catching Errors

In this example we ask the user to enter the date as mm/dd/year.

In the first date example, we only checked for the first slash. Here we check for the second slash also and also check for leap year.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
#include<iostream>
#include<string>
using namespace std;
int getInteger(string s) {
  int result=-1;
  try {
    result=stoi(s);
  }
  catch(invalid_argument&) {
    //do nothing, result is still -1 
  }
  return result;
}//getInteger
bool leapYear(int yr) {
  bool leap=false;
  if(yr%4==0) leap=true;
  if(yr%100==0 && yr%400!=0) leap=false;
  cout<<leap<<endl;
  return leap;
}//leapYear

int main(void) {
  string input;
  int month,day,year;
  cout<<"Enter the date as mm/dd/year:";
  cin>>input; //Example: 10/31/2016
  int p=input.find_first_of("/"); // Using example: p=2
  if(p<0) cout<<"not a valid date\n";
  else {
    month=getInteger(input.substr(0,p)); //Using example: month=10
    input=input.substr(p+1); //Using example: input="31/2016"
    p=input.find_first_of("/"); //Using example: p=2
    if(p<0) cout<<"not a valid date\n";
    else {
      day=getInteger(input.substr(0,p)); //Using example: day=31
      input=input.substr(p+1); //Using example: input="2016"
      year=getInteger(input); //Using example: year=2016
      if(month<0 || month>12 || day<0 || day>31 || year<0) 
        cout<<"not a valid date\n";
      else { //We have 3 integers, it still might not be a valid date!
        cout<<"You entered month="<<month<<" day="<<day<<" year="<<year<<endl;
        int days[]={0,31,28,31,30,31,30,31,31,30,31,30,31};
        if(leapYear(year)) days[2]=29;
        string months[]={"","January","February","March","April","May","June",
          "July","August","September","October","November","December"};
        if(day>days[month])  cout<<"There are not that many days in "<<months[month]<<"\n";
        else cout<<"There are "<<days[month]<<" days in "<<months[month]<<".\n";
      } //second slash found
  }//first slash found
  system("pause");
  return 0;
} //main 
CODE

Important note:

This is a lot of code, and we didn't really do anything but check for errors and print the number of days in the month if it was a valid date. In fact, it still might be an invalid date because we didn't check the year for anything. Now add a loop to let them retry, and then write something useful for the rest of the program!

When you learn to write classes, we will be able to move most of the error checking to the class.

NEXT: Structures combine data elements