Logical Error! Help Appreciated!!

These are member functions, where mm, dd, and yy are the only data members. For some reason when I run it, the first object is ok, but then on the second object it returns as false. and continues to ask the user for input. I know for sure there's something wrong with my validation for setDay, because it's asking the user to keep inputting values, despite the values being valid. Any suggestions on how to fix it?

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
  //setDay function
bool Date::setDay( int d ){

        bool validate = false;
        int monthsPerYear = 12;

        int date[monthsPerYear] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
        for ( int i = 1; i <= 12; i++){
                if ( mm == monthsPerYear && d <= date[i]){
                        dd = d;
                        validate = true;
                }

        }

        return(validate);
}

//input member function

void Date::input(){

        int m, y, d;

        do{
                cout << "Enter month: ";
                cin >> m;
                mm = m;
        } while(!setMonth(m));

        do{
                cout << "Enter date: ";
                cin >> d;
                dd = d;
        } while (!setDay(d));

        do{
                cout << "Enter year: ";
                cin >> y;
                yy = y;
        } while (!setYear(y));
}


Last edited on
Valid indexes for an array with size n are 0 through n-1. How is line 8 looking to you in setDay?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
bool Date::setDay( int d )
{
    const unsigned monthsPerYear = 12;
    const unsigned daysPerMonth[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};

    bool valid = false;
    if (d <= daysPerMonth[mm-1])    // assuming mm is in the range [1,12]
    {
        dd = d;
        valid = true;
    }

    return valid;
}
Last edited on
Topic archived. No new replies allowed.