Printing errors

Say I have the following constructor:

1
2
3
4
5
6
7
8
9
10
11
12
13
	Date::Date(int yr, short mt, short dy) {
		errCode = 0;
		do {
			inRangeYear(year) ? year = yr  : errCode = 2;
			inRangeMonth(mt) ? month = mt : errCode = 3;
			inRangeDay(dy) ? day = dy : errCode = 4;

		} while (errCode == 0);
		if ((year == 0000 || month == 00 || day == 00) && errCode == 0) {
			errCode = 1;
		}
		printErr(errCode);
	}


And my printErr() function is defined as:

1
2
3
4
5
6
7
8
9
	void Date::printErr(short err) {
		switch (err) {
			case 0: std::cout << "No errors" << err;
			case 1: std::cout << "Error code: " << err;
			case 2: std::cout << "Error code: " << err;
			case 3: std::cout << "Error code: " << err;
			case 4: std::cout << "Error code: " << err;
		}
	}


Assume all input is invalid; I want to print out Error code: 2 because I want it to terminate creation at first invalid input. The way I understand it, it will first fully loop through the loop, and return the last invalid error code (in this case, it'd be 1). How can I circumvent this? Will a do until loop achieve this for me? TIA
Last edited on

If you want to abort the loop if errCode is anything other than zero, you'll have to write code for that. Although I don't see the point of the loop at all. If nothing goes wrong, it will loop forever. That seems incorrect.

Does this meet your needs?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
Date::Date(int yr, short mt, short dy) 
{
  errCode = 0;

  if      ( !inRangeYear(year))  {  errCode = 2; }
  else if ( !inRangeMonth(mt))   {  errCode = 3; }
  else if ( !inRangeDay(dy))     {  errCode = 4; }
  else if ( yr== 0000 || mt== 00 || dy== 00) {errCode = 1;}

  if (errCode == 0)
  {
    year = yr;
    month = mt;
    day = dy;
  }

  printErr(errCode);
}

Last edited on
Topic archived. No new replies allowed.