Почему оператор if возвращает false, когда он должен быть истинным? - PullRequest
0 голосов
/ 07 августа 2020

Например, когда я ввожу 8 3 2020, которое должно сделать оператор if истинным, поскольку 8 3 2020 - это значения, которые можно найти в массиве, но вместо этого оно возвращает false

Вот main

/*
 * Homework 4  --  UPDATE as needed
*/ 

#include <iostream>
#include <fstream>
#include <iomanip>
#include <string>

#include "Appointment.h"
using namespace std;

                             
void callPrint (Time &TimeOrApptObject) { TimeOrApptObject.print();} 
int main(){
    int month, day, year, hour, minute,howLong;
    Appointment  myAppointments[19];

    ifstream HW4DataFileHandle;

    HW4DataFileHandle.open("Lab6Data.txt");
    while (!HW4DataFileHandle.eof( )) {
        for (int i = 1; i < 20;  i++) {
            HW4DataFileHandle>>month;
            HW4DataFileHandle>>day;
            HW4DataFileHandle>>year;
            HW4DataFileHandle>>hour;
            HW4DataFileHandle>>minute;
            HW4DataFileHandle>>howLong;
            myAppointments[i] = Appointment( month, day, year, hour, minute, howLong);
        }
        cout <<"enter a month" <<endl;
        cin >> month;
        cout <<"enter a day" <<endl;
        cin >> day;
        cout <<"enter a year"<<endl;
        cin >> year;
        Date myDate( month, day, year);

        cout <<"Appointments for" << month <<"/" << day <<"/" << year <<":"<< endl;

        for (int i = 0; i <13; i++){
            if ( friendTorCompare2Dates(myAppointments[i], myDate))
            { Time thisTime = myAppointments[i];
                thisTime.print();
                cout << endl;
            } 
        }
    }
}

Date.h

// Date.h -- Class Date    UPDATE  as needed
#ifndef DATE_H
#define DATE_H
class Date  {  
private:
    int month;
    int day;
    int year;
public:
Date(int m, int d, int y) : month(m), day(d), year(y)
    {
    }
    Date() = default;
    friend  bool friendTorCompare2Dates (const Date&,const Date& );

};
bool friendTorCompare2Dates (const Date& Right, const Date& Left)
{
    if (Right.month == Left.month && Right.day == Left.day && Right.year== Left.year)
        return true;
    else
        return false;
}

#endif

Time.h

//Time.h -- Class Time UPDATE  as needed
#ifndef TIME_H
#define TIME_H
using namespace std;
#include<iostream>

class Time {
private :
    int hour; int minute;
public:
Time(int h, int m) : hour(h)
    {
    }
    Time() = default;
    virtual void print() {
        cout << hour << " " << minute <<" "  ;
    }


};
#endif

Appointment.h

// Appointment.h -- Class Appointment   UPDATE as needed
//
#include "Time.h"
#include "Date.h"
#ifndef APPOINTMENT_H
#define APPOINTMENT_H
using namespace std;
class Appointment:  public Date, public Time {  
private:
    int howLong;
public:
Appointment(int month, int day, int year, int hour, int minute, int howLong) : 
    Date(month, day, year), Time(hour, minute), howLong(howLong)
    {
    }
 
    Appointment() = default; 
};

#endif

Что мне нужно изменить в моем коде так что когда я введу правильные значения, он вернет истину? Приведите пример в своем ответе, мы будем очень признательны. Спасибо за ваше время.

1 Ответ

3 голосов
/ 07 августа 2020

Ошибка здесь не в некорректном состоянии в if (который должен работать отлично), а в некорректном поведении программы. Здесь вы выйдете за границы:

for (int i = 1; i < 20;  i++) {
            HW4DataFileHandle>>month;
            HW4DataFileHandle>>day;
            HW4DataFileHandle>>year;
            HW4DataFileHandle>>hour;
            HW4DataFileHandle>>minute;
            HW4DataFileHandle>>howLong;
            myAppointments[i] = Appointment( month, day, year, hour, minute, howLong);
}

Поскольку вы объявили myAppointments как массив из 19 элементов, он получил индекс с допустимым диапазоном от 0 до 18. Не от 1 до 20. myAppointments[0] никогда не получал назначенные, 19-я и 20-я записи исчезли в Великом Неопределенном Неизвестном.

И здесь вы проверяете только часть массива, первые 13 элементов (включая неназначенный), это предназначено?

    for (int i = 0; i <13; i++){
        if ( friendTorCompare2Dates(myAppointments[i], myDate))
        { Time thisTime = myAppointments[i];
            thisTime.print();
            cout << endl;
        } 
    }

Это пример заблуждения «маги c число».

...