Catching Errors

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

We need to check for lots of errors. The slash could be missing, the conversion from string to int could fail, and then it could still be an invalid date.

Since there will be three integers to convert, it is easier to write a function and write the try/catch block just once. Since we know that month, day, and year must all be positive, we return -1 as a signal that the conversion failed.

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
#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

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
    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!
      int days[]={0,31,28,31,30,31,30,31,31,30,31,30,31};
      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";
      //We might have rejected Feb. 29 in a leap year! So we would also need a lepayear function, etc.
    }
  }
  system("pause");
  return 0;
} //main 
CODE

NEXT: Check for leap year