July 30, 2012

Finish the error checking before expending any resources

Class DayOfyear has three int, data members: year, month, and day.

void DayOfYear::setDate(int mm, int dd, int yy)
{
	if (mm >= 1 && mm <= 12)
		month = mm;
	else
		throw invalid_argument( "Month must be 1-12");

	if (yy >= 1900 && yy <= 2100)
		year == yy;
	else
		throw invalid_argument( "Year must be >= 1900 and <= 2100");

	if (( month == 2 && leapYear(year) && dd >= 1 && dd <= 29) ||
		(dd >= 1 && dd <= days[month]))
		day = dd;
	else
		throw invalid_argument( "Day is out of range for current month and year");
}

The constructor leaves one of the data member full of garbage. If there is an error, the assignments are a waste of time.

void DayOfYear::setDate(int mm, int dd, int yy)
{
	if (mm < 1 || mm > 12) {
		throw invalid_argument("Month must be 1-12");
	}

	if (yy < 1900 || yy > 2100) {
		throw invalid_argument("Year must be >= 1900 and <= 2100");
	}

	if (dd < 1 || dd > (mm == 2 && leapYear(yy) ? 29 : days[month]) {
		throw invalid_argument("Day is out of range for current month and year");
	}

	year = yy;
	month = mm;
	day = dd;
}
void DayOfYear::setDate(int mm, int dd, int yy)
{
	if (mm < 1 || mm > 12) {
		throw invalid_argument("Month must be 1-12");
	}

	if (yy < 1900 || yy > 2100) {
		throw invalid_argument("Year must be >= 1900 and <= 2100");
	}

	const int len = mm == 2 && leapYear(yy) ? 29 : days[month];
	if (dd < 1 || dd > len) {
		throw invalid_argument("Day is out of range for current month and year");
	}

	year = yy;
	month = mm;
	day = dd;
}

The error messages should display the bad values.

Unsnarl the control structure

The data member guessAns is a string object. The memmber function returns true if this string consists of exactly NUM_DIGIT digits. The return false in the loop is executed if the character being examined is not a digit.

bool game::checkFormat()
{
	if (guessAns.length() == NUM_DIGIT) {
		for (int i = 0; i < NUM_DIGIT; i++) {
			if (guessAns.compare(i,1,"0") < 0
				|| guessAns.compare(i, 1, "9") > 0) {
				return false;
			}
		}
	} else {
		return false;
	}

	return true;
}
bool game::checkFormat() const
{
	if (guessAns.length() != NUM_DIGIT) {
		//The lenghth of the string is wrong.
		return false;
	}

	for (int i = 0; i < NUM_DIGIT; ++i) {
		if (guessAns.compare(i, 1, "0") < 0
			|| guessAns.compare(i, 1, "9") > 0) {
			return false;
		}
	}

	return true;
}