Форум программистов, компьютерный форум, киберфорум
С++ для начинающих
Войти
Регистрация
Восстановить пароль
Блоги Сообщество Поиск  
 
 
Рейтинг 5.00/16: Рейтинг темы: голосов - 16, средняя оценка - 5.00
7 / 6 / 1
Регистрация: 04.10.2021
Сообщений: 268

Записать в файл массив обьектов класса

11.09.2022, 13:48. Показов 3688. Ответов 31
Метки c++ (Все метки)

Студворк — интернет-сервис помощи студентам
hospital.h

C++
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
#ifndef HOSPITALREGISTRY_HOSPITAL_H
#define HOSPITALREGISTRY_HOSPITAL_H
 
#include <iostream>
#include <ostream>
#include <string>
#include <fstream>
 
using namespace std;
 
class Patient {
protected:
    string name;
    string surname;
    string phone;
    int age;
 
public:
    void SetPatientName(string name);
 
    void SetPatientSurname(string surname);
 
    void SetPatientPhone(string phone);
 
    void SetPatientAge(int age);
 
    string GetPatientName();
 
    string GetPatientSurname();
 
    string GetPatientPhone();
 
    int GetPatientAge();
};
 
class Doctor {
protected:
    string name;
    string surname;
    string qualification;
    int numberOfDoctorPatients;
    Patient *patients;
 
public:
    Doctor() {
        name = "";
        surname = "";
        qualification = "";
        numberOfDoctorPatients = 0;
        patients = new Patient[numberOfDoctorPatients];
    };
 
    Doctor(string name, string surname, string qualification, int numberOfDoctorPatients, Patient *patients) {
        this->name = name;
        this->surname = surname;
        this->qualification = qualification;
        this->numberOfDoctorPatients = numberOfDoctorPatients;
        this->patients = new Patient[numberOfDoctorPatients];
 
    }
 
    Patient NewPatientToDoctor(string patientName, string patientSurname, string patientPhone, int patientAge);
 
    Patient AddPatientToDoctor(Doctor *&doctorsArray, int doctorChoose);
 
    void SetDoctorName(string name);
 
    void SetDoctorSurname(string surname);
 
    void SetDoctorQualification(string qualification);
 
    void SetDoctorNumberOfPatients(int numberOfDoctorPatients);
 
    void SetDoctorPatients(Patient *patients);
 
    string GetDoctorName();
 
    string GetDoctorSurname();
 
    string GetDoctorQualification();
 
    int GetNumberOfDoctorPatients();
 
    Patient GetDoctorPatients();
};
 
 
class Registry {
 
private:
    Patient patient;
    Doctor doctor;
    string info;
 
    struct date {
        int day;
        int month;
        int year;
    };
 
    date date;
 
 
public:
    Registry newAppointment(Doctor *doctorsArray, int numberOfDoctors);
 
    void AddPatientAppointment(Doctor *&doctorsArray, Registry *&appointmentArray, int &numberOfAllPatients,
                               int doctorChoose);
 
    void RemovePatientAppointment(Registry *appointmentArray, int numberOfAllPatients);
 
    void EditPatientAppointment(Registry *appointmentArray, int numberOfAllPatients);
 
    void ShowAllPatientAppointments(Registry *appointmentArray, int numberOfAllPatients);
 
    void ShowDoctorAppointments(Registry *appointmentArray, int numberOfAllPatients);
};
 
 
class File {
 
private:
    string extension = ".txt";
    string dataFileName = "data";
    string varFileName = "var";
    string dataFilePath =
            "/Users/otkisyan/CLionProjects/HospitalRegistry/cmake-build-debug/userfiles/" + dataFileName + extension;
    string varFilePath =
            "/Users/otkisyan/CLionProjects/HospitalRegistry/cmake-build-debug/userfiles/" + varFileName + extension;
 
public:
    void CheckFileExists();
 
    void CreateFile();
 
    void DeleteFile();
 
    void ReadFile(int &numberOfAllPatients, Registry *appointmentArray);
 
    void RewriteFile(int numberOfAllPatients, Registry *appointmentArray);
};
 
 
#endif //HOSPITALREGISTRY_HOSPITAL_H

registry-class-implement
C++
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
#include "hospital.h"
 
Registry Registry::newAppointment(Doctor *doctorsArray, int numberOfDoctors) {
 
    Registry newAppointment;
 
    string name;
    string surname;
    string phone;
    int age;
 
    cout << "Введіть ім'я клієнта: " << endl;
    cout << "➡ ";
    cin >> name;
    newAppointment.patient.SetPatientName(name);
 
    cout << "Введіть фамілію клієнта: " << endl;
    cout << "➡ ";
    cin >> surname;
    newAppointment.patient.SetPatientSurname(surname);
 
    cout << "Введіть телефон клієнта: " << endl;
    cout << "➡ ";
    cin >> phone;
    newAppointment.patient.SetPatientPhone(phone);
 
    cout << "Введіть вік клієнта" << endl;
    cout << "➡ ";
    cin >> age;
    newAppointment.patient.SetPatientAge(age);
 
    cout << "Введіть скаргу клієнта" << endl;
    cout << "➡ ";
    cin >> newAppointment.info;
 
    cout << "Введіть дату прийому: " << endl;
    cout << "День (1-31): " << endl;
    cout << "➡ ";
    cin >> newAppointment.date.day;
    cout << "Місяць: " << endl;
    cout << "➡ ";
    cin >> newAppointment.date.month;
    cout << "Рік: " << endl;
    cout << "➡ ";
    cin >> newAppointment.date.year;
 
 
 
    cout << "Оберіть номер необхідного лікаря" << endl;
    for (int i = 0; i < numberOfDoctors; i++) {
        cout << "Номер лікаря: " << i << endl;
        cout << "Ім'я лікаря: " << doctorsArray[i].GetDoctorName() << endl;
        cout << "Фамілія лікаря: " << doctorsArray[i].GetDoctorSurname() << endl;
        cout << "Кваліфікація лікаря: " << doctorsArray[i].GetDoctorQualification() << endl;
 
    }
 
    int doctorChoose = 0;
    cout << "➡ ";
    cin >> doctorChoose;
 
    newAppointment.doctor.SetDoctorName(doctorsArray[doctorChoose].GetDoctorName());
    newAppointment.doctor.SetDoctorSurname(doctorsArray[doctorChoose].GetDoctorSurname());
    newAppointment.doctor.SetDoctorQualification(doctorsArray[doctorChoose].GetDoctorQualification());
 
    return newAppointment;
 
}
 
 
void Registry::AddPatientAppointment(Doctor *&doctorsArray, Registry *&appointmentArray, int &numberOfAllPatients,
                                     int doctorChoose) {
 
    File file;
 
    Registry *appointmentArrayTemp = new Registry[numberOfAllPatients + 1];
 
    for (int j = 0; j < numberOfAllPatients; j++) {
        appointmentArrayTemp[j] = appointmentArray[j];
    }
 
    delete[] appointmentArray;
    appointmentArray = appointmentArrayTemp;
 
    numberOfAllPatients++;
    int i = numberOfAllPatients - 1;
    appointmentArray[i] = appointmentArray->newAppointment(doctorsArray, numberOfAllPatients);
 
 
}
 
void Registry::ShowAllPatientAppointments(Registry *appointmentArray, int numberOfAllPatients) {
 
    File file;
 
    for (int i = 0; i < numberOfAllPatients; i++) {
        cout << "Номер пацієнта: " << i << endl;
        cout << "Ім'я пацієнта: " << appointmentArray[i].patient.GetPatientName() << endl;
        cout << "Фамілія пацієнта: " << appointmentArray[i].patient.GetPatientSurname() << endl;
        cout << "Вік пацієнта: " << appointmentArray[i].patient.GetPatientAge() << endl;
        cout << endl;
 
        cout << "Назначений лікарь: " << endl;
        cout << "Ім'я лікаря: " << appointmentArray[i].doctor.GetDoctorName() << endl;
        cout << "Фамілія лікаря: " << appointmentArray[i].doctor.GetDoctorSurname() << endl;
        cout << "Кваліфікація лікаря: " << appointmentArray[i].doctor.GetDoctorQualification() << endl;
 
        cout << "Дата прийому: " << appointmentArray->date.day << "." << appointmentArray->date.month
             << "." << appointmentArray->date.year;
    }
 
}
file-class-implement.cpp
C++
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
#include "hospital.h"
 
void File::CheckFileExists() {
 
    ifstream var;
    ifstream data;
 
    bool varExists = false;
    bool dataExists = false;
 
    var.open(varFilePath);
    //data.open(dataFilePath);
 
    if (var) {
        varExists = true;
        var.close();
    }
 
    data.open(dataFilePath);
 
    if (data) {
        dataExists = true;
        data.close();
    }
 
    if (varExists == false && dataExists == false) {
        File::CreateFile();
    }
 
}
 
void File::CreateFile() {
 
    ofstream var;
    ofstream data;
 
    var.open(varFilePath.c_str(), ios::binary | ios::out);
    var.close();
 
    data.open(dataFilePath.c_str(), ios::binary | ios::out);
    data.close();
}
 
void File::DeleteFile() {
    remove(dataFilePath.c_str());
    remove(varFilePath.c_str());
}
 
void File::ReadFile(int &numberOfAllPatients, Registry *appointmentArray) {
 
    ifstream var;
    ifstream data;
 
    var.open(varFilePath.c_str(), ios::binary);
    var.read((char *) &numberOfAllPatients, sizeof(numberOfAllPatients));
    var.close();
 
    data.open(dataFilePath.c_str(), ios::binary);
    for (int i = 0; i < numberOfAllPatients; i++) {
        data.read((char *) &appointmentArray[i], sizeof(appointmentArray[i]));
    }
    data.close();
 
}
 
void File::RewriteFile(int numberOfAllPatients, Registry *appointmentArray) {
 
    ofstream var;
    ofstream data;
 
    var.open(varFilePath.c_str(), ios::binary);
    var.write((char *) &numberOfAllPatients, sizeof(numberOfAllPatients));
    var.close();
 
    data.open(dataFilePath.c_str(), ios::binary);
    for (int i = 0; i < numberOfAllPatients; i++) {
        data.write((char *) &appointmentArray, sizeof(appointmentArray[i]));
    }
 
}
main.cpp
C++
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
#include "hospital.h"
 
int main() {
 
    File file;
    Registry *registryArray = nullptr;
    Doctor *doctorsArray = nullptr;
    file.CheckFileExists();
 
 
    int numberOfAllPatients = 0;
    int numberOfDoctors = 1;
    int doctorChoose = 0;
 
    doctorsArray = new Doctor[numberOfDoctors]{
            {"Егор", "Родионов", "Аллерголог", 0, {}},
 
    };
 
    registryArray = new Registry[numberOfAllPatients];
 
    file.ReadFile(numberOfAllPatients, registryArray);
 
    registryArray->AddPatientAppointment(doctorsArray, registryArray, numberOfAllPatients, doctorChoose);
    file.RewriteFile(numberOfAllPatients, registryArray);
    registryArray->ShowAllPatientAppointments(registryArray, numberOfAllPatients);
 
 
    return 0;
 
}
 
 
}
Всем привет, делаю типо регистратуру для больницы, но не получается записать и прочитать файл, я записываю массив обьектов класса Registry в файл, но оно либо ничего не записывает, либо записывает какой - то мусор, я так понимаю это связано либо с тем что оно не может записать string, либо потому-что в класс Registry содержит в себе также обьекты Doctor и Patient. Прошу помощи.
0
cpp_developer
Эксперт
20123 / 5690 / 1417
Регистрация: 09.04.2010
Сообщений: 22,546
Блог
11.09.2022, 13:48
Ответы с готовыми решениями:

Записать в текстовый файл массив обьектов с полями разных типов
Записать в текстовый файл массив обьектов с полями разных типов, и потом считать из файла данные и записать в массив по типу идентичному из...

Записать массив объектов класса в файл
Доброго времени суток вопрос скорее теоретический, полазил в гугле и немого разочаровался. Пишут что пхп язык типизированный и все типы...

как записать массив данных класса в бинарный файл
у меня такая проблема. есть программа которая сохраняет персонал в программу и каждому создает текстовый файл. после записи она может...

31
 Аватар для ram876
759 / 456 / 213
Регистрация: 19.12.2016
Сообщений: 1,815
14.09.2022, 19:06
Студворк — интернет-сервис помощи студентам
Цитата Сообщение от vadyansky Посмотреть сообщение
пустая строка
Вот пример ошибки
0
Модератор
Эксперт С++
 Аватар для zss
13794 / 10986 / 6492
Регистрация: 18.12.2011
Сообщений: 29,287
15.09.2022, 14:39
cout << "Введіть ім'я клієнта: " << endl;
cout << "➡ ";
cin >> ws;
getline(cin, name);
1. зачем здесь cin>>ws ?
Вы реально считаете, что пользователь при вводе обязательно в начале каждой строки будет вводить лишний символ?
И, кстати, я не нашел, где эта ws объявлена.

2. При вводе вы не приняли никаких действий для перевода Досовской кодировки в кодировку Windows.
Почитайте
Русские шрифты в консоли
1
7 / 6 / 1
Регистрация: 04.10.2021
Сообщений: 268
15.09.2022, 14:59  [ТС]
zss, cin >> ws, я написал потомучто getline почему то пропускает иногда ввод, насчет второго, у меня мак а не виндовс
0
Модератор
Эксперт С++
 Аватар для zss
13794 / 10986 / 6492
Регистрация: 18.12.2011
Сообщений: 29,287
15.09.2022, 16:11
Цитата Сообщение от vadyansky Посмотреть сообщение
getline почему то пропускает иногда ввод
Getline ничего не пропускает.
Это Вы неаккуратно работаете с оператором cin>>xxxxx
забывая, что он вводит данные до пробельного символа (в т.ч. и до enter) ОСТАВЛЯЯ ЕГО В ПОТОКЕ.
Соответственно getline читает этот enter как пустую строку.
Поэтому везде после окончания ввода по cin>>>xxxx
пропускайте оставшиеся символы, например, так:
C++
1
2
3
4
5
6
    cin >> doctorChoose;
    char c;
    while( (c=cin.get())!='\n' )
      ; // пустой оператор
   return is;
}
Или, если уверены, что ничего, кроме '\n' больше не остается:
C++
1
(cin >> doctorChoose).get();
1
7 / 6 / 1
Регистрация: 04.10.2021
Сообщений: 268
15.09.2022, 16:30  [ТС]
zss,


Добавлено через 3 минуты
Цитата Сообщение от zss Посмотреть сообщение
cin >> doctorChoose;
    char c;
    while( (c=cin.get())!='\n' )
      ; // пустой оператор
   return is;
это только с int такая проблема?

Добавлено через 2 минуты
Цитата Сообщение от vadyansky Посмотреть сообщение
int use = 0;
    int work = 0;
do {
        cin >> use;
        switch (use) {
            case 1: {
                work = 1;
                file.ReadFile(patientsArray, numberOfPatients, doctorsArray, numberOfDoctors, appointmentsArray);
                appointmentsArray->AddPatient(patientsArray, numberOfPatients);
                appointmentsArray->AddPatientAppointment(appointmentsArray , patientsArray, doctorsArray,
                                                         numberOfPatients, numberOfDoctors);
file.RewriteFile(patientsArray, numberOfPatients, doctorsArray, numberOfDoctors, appointmentsArray);
                cout << "Бажаєте продовжити роботу? 1 - так, 2 - ні" << endl;
                cout << "➡ ";
                cin >> work;
                break;
            }
case 2: {
                work = 1;
file.ReadFile(patientsArray, numberOfPatients, doctorsArray, numberOfDoctors, appointmentsArray);
                appointmentsArray->ShowAllPatientAppointments(appointments Array, patientsArray, doctorsArray,
                                                              numberOfPatients);
                cout << "Бажаєте продовжити роботу? 1 - так, 2 - ні" << endl;
                cout << "➡ ";
                cin >> work;
                break;
            }
case 3: {
file.ReadFile(patientsArray, numberOfPatients, doctorsArray, numberOfDoctors, appointmentsArray);
                appointmentsArray->ShowDoctorAppointments(appointmentsArra y, patientsArray, doctorsArray,
                                                          numberOfPatients, numberOfDoctors);
            }
        }
    } while (work == 1);
return 0;
}
Тоесть мне вот тут тоже так надо будет сделать?
0
Модератор
Эксперт С++
 Аватар для zss
13794 / 10986 / 6492
Регистрация: 18.12.2011
Сообщений: 29,287
15.09.2022, 16:40
Не только для int, а для любой переменной xxxx, которую вводите по cin>>xxxx;
Если идет подряд несколько cin>>xxxx;cin>>yyyy;
то между ними символ '\n' пропускать не обязательно.
Надо только после последнего.

Цитата Сообщение от vadyansky Посмотреть сообщение
cin >> use;
Здесь надо
C++
1
(cin >> use).get();
и
C++
1
(cin >> work).get();
1
7 / 6 / 1
Регистрация: 04.10.2021
Сообщений: 268
15.09.2022, 17:02  [ТС]
Цитата Сообщение от zss Посмотреть сообщение
cin >> doctorChoose;
а почему тут не (cin >> doctorChoose).get();

Добавлено через 5 минут
C++
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
Registry
Registry::NewAppointment(Patient *patientsArray, Doctor *doctorsArray, int numberOfDoctors, int numberOfPatients) {
 
    Registry newAppointment;
 
    cout << "Введіть дату прийому: " << endl;
    cout << "День (1-31): " << endl;
    cout << "➡ ";
    (cin >> newAppointment.date.day).get();
 
    cout << "Місяць (1-12): " << endl;
    cout << "➡ ";
    (cin >> newAppointment.date.month).get();
 
    cout << "Рік (0-2022): " << endl;
    cout << "➡ ";
    (cin >> newAppointment.date.year).get();
 
    cout << "Оберіть номер необхідного лікаря" << endl;
    for (int i = 0; i < numberOfDoctors; i++) {
        cout << "Номер лікаря: " << i << endl;
        cout << "Ім'я лікаря: " << doctorsArray[i].GetDoctorName() << endl;
        cout << "Фамілія лікаря: " << doctorsArray[i].GetDoctorSurname() << endl;
        cout << "Кваліфікація лікаря: " << doctorsArray[i].GetDoctorQualification() << endl;
        cout << endl;
 
    }
 
    cout << "➡ ";
    int choosedDoctor = 0;
    cin >> choosedDoctor;
    char c;
    while( (c=cin.get())!='\n' )
        ;
 
    newAppointment.doctorCode = choosedDoctor;
    newAppointment.patientCode = patientsArray[numberOfPatients - 1].GetPatientCode();
 
    return newAppointment;
 
}
Там где char c, cin.get() оно подписывает что значение никогда не используеться
0
Модератор
Эксперт С++
 Аватар для zss
13794 / 10986 / 6492
Регистрация: 18.12.2011
Сообщений: 29,287
15.09.2022, 18:09
Еще раз
Цитата Сообщение от vadyansky Посмотреть сообщение
C++
1
2
3
4
cin >> choosedDoctor;
 char c;
 while( (c=cin.get())!='\n' )
    ;
Если уверены, что пользователь не будет вводить лишних символов, а сразу после ввода числа нажмет enter,
то, естественно, cin.get() можете сделать только один раз, т.е.
C++
1
(cin >> choosedDoctor).get();
Если не понятно, что это одно и то же, то вспомните, что operator>> возвращает ссылку на istream, т.е cin.
И следующей операцией, соответственно, будет cin.get()

Цитата Сообщение от vadyansky Посмотреть сообщение
подписывает, что значение никогда не используется
Пусть подписывает, Вы же знаете, что оно больше не нужно.
1
7 / 6 / 1
Регистрация: 04.10.2021
Сообщений: 268
16.09.2022, 09:40  [ТС]
zss,

main.cpp
C++
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
#include "hospital.h"
 
int main() {
    int numberOfPatients = 0;
    int numberOfDoctors = 2;
 
    File file;
    Patient *patientsArray = new Patient[numberOfPatients];
    Registry *appointmentsArray = new Registry[numberOfPatients];
 
    Doctor *doctorsArray = new Doctor[numberOfDoctors]{{"Егор", "Родионов", "Аллерголог",  0},
                                                       {"Ярик", "Бачок",    "Травматолог", 1}
    };
 
    file.CheckFileExists();
 
    int use = 0;
    int work = 0;
 
    do {
        (cin >> use).get();
 
        switch (use) {
            case 1: {
                work = 1;
                file.ReadFile(patientsArray, numberOfPatients, doctorsArray, numberOfDoctors, appointmentsArray);
                appointmentsArray->AddPatient(patientsArray, numberOfPatients);
                appointmentsArray->AddPatientAppointment(appointmentsArray, patientsArray, doctorsArray,
                                                         numberOfPatients, numberOfDoctors);
 
                file.RewriteFile(patientsArray, numberOfPatients, doctorsArray, numberOfDoctors, appointmentsArray);
                cout << "Бажаєте продовжити роботу? 1 - так, 2 - ні" << endl;
                cout << "➡ ";
                (cin >> work).get();
                break;
            }
 
            case 2: {
                work = 1;
 
                file.ReadFile(patientsArray, numberOfPatients, doctorsArray, numberOfDoctors, appointmentsArray);
                appointmentsArray->ShowAllPatientAppointments(appointmentsArray, patientsArray, doctorsArray,
                                                              numberOfPatients);
                cout << "Бажаєте продовжити роботу? 1 - так, 2 - ні" << endl;
                cout << "➡ ";
                (cin >> work).get();
                break;
            }
 
            case 3: {
 
                file.ReadFile(patientsArray, numberOfPatients, doctorsArray, numberOfDoctors, appointmentsArray);
                appointmentsArray->ShowDoctorAppointments(appointmentsArray, patientsArray, doctorsArray,
                                                          numberOfPatients, numberOfDoctors);
                cout << "Бажаєте продовжити роботу? 1 - так, 2 - ні" << endl;
                cout << "➡ ";
                (cin >> work).get();
                break;
            }
 
            case 4: {
                file.ReadFile(patientsArray, numberOfPatients, doctorsArray, numberOfDoctors, appointmentsArray);
                appointmentsArray->RemovePatientAppointment(patientsArray, appointmentsArray, numberOfPatients);
                file.RewriteFile(patientsArray, numberOfPatients, doctorsArray, numberOfDoctors, appointmentsArray);
                cout << "Бажаєте продовжити роботу? 1 - так, 2 - ні" << endl;
                cout << "➡ ";
                (cin >> work).get();
                break;
            }
        }
    } while (work == 1);
 
    return 0;
 
}
file-class-implement.cpp
C++
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
#include "hospital.h"
 
ostream &operator<<(ostream &os, Patient &p) {
    os << p.name << ' ' << p.surname << ' ' << p.phone << ' ' << p.age << ' ' << p.patientCode << endl;
    return os;
}
 
istream &operator>>(istream &is, Patient &p) {
    is >> p.name >> p.surname >> p.phone >> p.age >> p.patientCode;
 
    return is;
}
 
ostream &operator<<(ostream &os, Doctor &d) {
    os << d.name << ' ' << d.surname << ' ' << d.qualification << ' ' << d.doctorCode << endl;
    return os;
}
 
istream &operator>>(istream &is, Doctor &d) {
    is >> d.name >> d.surname >> d.qualification >> d.doctorCode;
 
    return is;
}
 
ostream &operator<<(ostream &os, Registry &r) {
    os << r.date.day << ' ' << r.date.month << ' ' << r.date.year << ' ' << r.doctorCode << ' '
       << r.patientCode << endl;
    return os;
}
 
istream &operator>>(istream &is, Registry &r) {
    is >> r.date.day >> r.date.month >> r.date.year >> r.doctorCode >> r.patientCode;
 
    return is;
}
 
void File::CheckFileExists() {
 
    ifstream patientsFile;
    ifstream numberOfPatientsFile;
    ifstream doctorsFile;
    ifstream numberOfDoctorsFile;
    ifstream appointmentsFile;
 
    bool patientsFileExists = false;
    bool numberOfPatientsFileExists = false;
    bool doctorsFileExists = false;
    bool numberOfDoctorsFileExists = false;
    bool appointmentsFileExists = false;
 
    patientsFile.open(patientsFilePath);
 
    if (patientsFile) {
        patientsFileExists = true;
        patientsFile.close();
    }
 
    numberOfPatientsFile.open(numberOfPatientsFilePath);
 
    if (numberOfPatientsFile) {
        numberOfPatientsFileExists = true;
        numberOfPatientsFile.close();
    }
 
    doctorsFile.open(doctorsFilePath);
 
    if (doctorsFile) {
        doctorsFileExists = true;
        doctorsFile.close();
    }
 
    numberOfDoctorsFile.open(numberOfDoctorsFilePath);
 
    if (numberOfDoctorsFile) {
        numberOfDoctorsFileExists = true;
        numberOfDoctorsFile.close();
    }
 
    appointmentsFile.open(appointmentsFilePath);
 
    if (appointmentsFile) {
        appointmentsFileExists = true;
        appointmentsFile.close();
    }
 
    if (patientsFileExists == false || numberOfPatientsFileExists == false || doctorsFileExists == false ||
        numberOfDoctorsFileExists == false || appointmentsFileExists == false) {
        cout << "Необхідних файлів не існує або файловій системі відбувся збій, всі данні будуть видалені" << endl;
        CreateFile();
    }
}
 
void File::CreateFile() {
 
    ofstream patientsFile;
    ofstream numberOfPatientsFile;
    ofstream doctorsFile;
    ofstream numberOfDoctorsFile;
    ofstream appointmentsFile;
 
    patientsFile.open(patientsFilePath.c_str(), ios::binary | ios::out);
    patientsFile.close();
 
    numberOfPatientsFile.open(numberOfPatientsFilePath.c_str(), ios::binary | ios::out);
    numberOfPatientsFile.close();
 
    doctorsFile.open(doctorsFilePath.c_str(), ios::binary | ios::out);
    numberOfDoctorsFile.open(numberOfDoctorsFilePath.c_str(), ios::binary | ios::out);
 
    appointmentsFile.open(appointmentsFilePath.c_str(), ios::binary | ios::out);
 
}
 
void File::DeleteFile() {
    remove(patientsFilePath.c_str());
    remove(numberOfPatientsFilePath.c_str());
    remove(doctorsFilePath.c_str());
    remove(numberOfDoctorsFilePath.c_str());
    remove(appointmentsFilePath.c_str());
}
 
void File::ReadFile(Patient *patientsArray, int &numberOfPatients, Doctor *doctorsArray, int &numberOfDoctors,
                    Registry *appointmentsArray) {
 
    ifstream patientsFile;
    ifstream numberOfPatientsFile;
    ifstream doctorsFile;
    ifstream numberOfDoctorsFile;
    ifstream appointmentsFile;
 
    numberOfPatientsFile.open(numberOfPatientsFilePath.c_str());
 
    if (!numberOfPatientsFile) {
        cout << "Помилка при відкритті файлу numberOfPatients";
        exit(1);
    }
 
    numberOfPatientsFile.read((char *) &numberOfPatients, sizeof(numberOfPatients));
    numberOfPatientsFile.close();
 
    patientsFile.open(patientsFilePath.c_str());
 
    if (!patientsFile) {
        cout << "Помилка при відкритті файлу patients";
        exit(1);
    }
 
    for (int i = 0; i < numberOfPatients; i++) {
        patientsFile >> patientsArray[i];
    }
 
    patientsFile.close();
 
    numberOfDoctorsFile.open(numberOfDoctorsFilePath.c_str());
 
    if (!numberOfDoctorsFile) {
        cout << "Помилка при відкритті файлу numberOfDoctors";
        exit(1);
    }
 
    numberOfDoctorsFile.read((char *) &numberOfDoctors, sizeof(numberOfDoctors));
    numberOfDoctorsFile.close();
 
    doctorsFile.open(doctorsFilePath.c_str());
 
    if (!doctorsFile) {
        cout << "Помилка при відкритті файлу doctors";
        exit(1);
    }
 
    for (int i = 0; i < numberOfDoctors; i++) {
        doctorsFile >> doctorsArray[i];
    }
    doctorsFile.close();
 
    appointmentsFile.open(appointmentsFilePath.c_str());
 
    if (!appointmentsFile) {
        cout << "Помилка при відкритті файлу appointments";
        exit(1);
    }
 
    for (int i = 0; i < numberOfPatients; i++) {
        appointmentsFile >> appointmentsArray[i];
    }
    appointmentsFile.close();
 
}
 
void File::RewriteFile(Patient *patientsArray, int &numberOfPatients, Doctor *doctorsArray, int &numberOfDoctors,
                       Registry *appointmentsArray) {
 
    ofstream patientsFile;
    ofstream numberOfPatientsFile;
    ofstream doctorsFile;
    ofstream numberOfDoctorsFile;
    ofstream appointmentsFile;
 
    numberOfPatientsFile.open(numberOfPatientsFilePath.c_str());
 
    if (!numberOfPatientsFile) {
        cout << "Помилка при відкритті файлу numberOfPatients";
        exit(1);
    }
 
    numberOfPatientsFile.write((char *) &numberOfPatients, sizeof(numberOfPatients));
    numberOfPatientsFile.close();
 
    patientsFile.open(patientsFilePath.c_str());
 
    if (!patientsFile) {
        cout << "Помилка при відкритті файлу patients";
        exit(1);
    }
 
    for (int i = 0; i < numberOfPatients; i++) {
        patientsFile << patientsArray[i];
    }
    patientsFile.close();
 
    numberOfDoctorsFile.open(numberOfDoctorsFilePath.c_str());
 
    if (!numberOfDoctorsFile) {
        cout << "Помилка при відкритті файлу numberOfDoctors";
        exit(1);
    }
 
    numberOfDoctorsFile.write((char *) &numberOfDoctors, sizeof(numberOfDoctors));
    numberOfDoctorsFile.close();
 
    doctorsFile.open(doctorsFilePath.c_str());
 
    if (!doctorsFile) {
        cout << "Помилка при відкритті файлу doctors";
        exit(1);
    }
 
    for (int i = 0; i < numberOfDoctors; i++) {
        doctorsFile << doctorsArray[i];
    }
    doctorsFile.close();
 
    appointmentsFile.open(appointmentsFilePath.c_str());
 
    if (!appointmentsFile) {
        cout << "Помилка при відкритті файлу appointments";
        exit(1);
    }
 
    for (int i = 0; i < numberOfPatients; i++) {
        appointmentsFile << appointmentsArray[i];
    }
    appointmentsFile.close();
 
}
registry-class-implement.cpp
C++
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
#include "hospital.h"
 
Patient Registry::NewPatient() {
 
    Patient newPatient;
 
    string name;
    string surname;
    string phone;
    int age;
 
    cout << "Введіть ім'я клієнта: " << endl;
    cout << "➡ ";
    getline(cin, name);
    newPatient.SetPatientName(name);
 
    cout << "Введіть фамілію клієнта: " << endl;
    cout << "➡ ";
    getline(cin, surname);
    newPatient.SetPatientSurname(surname);
 
    cout << "Введіть номер телефону клієнта: " << endl;
    cout << "➡ ";
    getline(cin, phone);
    newPatient.SetPatientPhone(phone);
 
    cout << "Введіть вік клієнта" << endl;
    cout << "➡ ";
    cin >> age;
 
    char c;
    while((c=cin.get())!='\n')
        ;
 
    newPatient.SetPatientAge(age);
 
    return newPatient;
}
 
 
void Registry::AddPatient(Patient *&patientsArray, int &numberOfPatients) {
 
    Patient *patientsArrayTemp = new Patient[numberOfPatients + 1];
 
    for (int j = 0; j < numberOfPatients; j++) {
        patientsArrayTemp[j] = patientsArray[j];
    }
 
    delete[] patientsArray;
    patientsArray = patientsArrayTemp;
 
    numberOfPatients++;
    int i = numberOfPatients - 1;
 
    patientsArray[i] = NewPatient();
    patientsArray[i].SetPatientCode(i);
 
 
}
 
void Registry::RemovePatient(Patient *&patientsArray, int &numberOfPatients, int patientToDelete) {
 
    Patient *patientsArrayTemp = new Patient[numberOfPatients - 1];
 
    for (int i = 0; i < patientToDelete; i++) {
        patientsArrayTemp[i] = patientsArray[i];
    }
 
    for (int i = patientToDelete + 1; i < numberOfPatients; i++) {
        patientsArrayTemp[i - 1] = patientsArray[i];
        patientsArrayTemp[i - 1].SetPatientCode(patientsArrayTemp[i - 1].GetPatientCode() - 1);
    }
 
    delete[] patientsArray;
    numberOfPatients--;
    patientsArray = patientsArrayTemp;
 
 
}
 
Registry
Registry::NewAppointment(Patient *patientsArray, Doctor *doctorsArray, int numberOfDoctors, int numberOfPatients) {
 
    Registry newAppointment;
 
    cout << "Введіть дату прийому: " << endl;
    cout << "День (1-31): " << endl;
    cout << "➡ ";
    cin >> newAppointment.date.day;
 
    cout << "Місяць (1-12): " << endl;
    cout << "➡ ";
    cin >> newAppointment.date.month;
 
    cout << "Рік (0-2022): " << endl;
    cout << "➡ ";
    cin >> newAppointment.date.year;
 
    cout << "Оберіть номер необхідного лікаря" << endl;
    for (int i = 0; i < numberOfDoctors; i++) {
        cout << "Номер лікаря: " << i << endl;
        cout << "Ім'я лікаря: " << doctorsArray[i].GetDoctorName() << endl;
        cout << "Фамілія лікаря: " << doctorsArray[i].GetDoctorSurname() << endl;
        cout << "Кваліфікація лікаря: " << doctorsArray[i].GetDoctorQualification() << endl;
        cout << endl;
 
    }
 
    cout << "➡ ";
    int choosedDoctor = 0;
    cin >> choosedDoctor;
    char c;
    while( (c=cin.get())!='\n' )
        ;
 
    newAppointment.doctorCode = choosedDoctor;
    newAppointment.patientCode = patientsArray[numberOfPatients - 1].GetPatientCode();
 
    return newAppointment;
 
}
 
 
void Registry::AddPatientAppointment(Registry *&appointmentsArray, Patient *patientsArray, Doctor *doctorsArray,
                                     int numberOfPatients, int numberOfDoctors) {
 
    Registry *appointmentsArrayTemp = new Registry[numberOfPatients + 1];
 
    for (int i = 0; i < numberOfPatients; i++) {
        appointmentsArrayTemp[i] = appointmentsArray[i];
    }
 
    delete[] appointmentsArray;
    appointmentsArray = appointmentsArrayTemp;
 
    int i = numberOfPatients - 1;
 
    appointmentsArray[i] = appointmentsArray->NewAppointment(patientsArray, doctorsArray, numberOfDoctors,
                                                             numberOfPatients);
}
 
void Registry::RemovePatientAppointment(Patient *&patientsArray, Registry *&appointmentsArray, int &numberOfPatients) {
 
    int patientToDelete;
    cout << "Введіть номер пацієнта якого необхідно видалити" << endl;
    cout << "➡ ";
    cin >> patientToDelete;
 
    Registry *appointmentsArrayTemp = new Registry[numberOfPatients - 1];
 
    for (int i = 0; i < patientToDelete; i++) {
        appointmentsArrayTemp[i] = appointmentsArray[i];
    }
 
    for (int i = patientToDelete + 1; i < numberOfPatients; i++) {
        appointmentsArrayTemp[i - 1] = appointmentsArray[i];
        appointmentsArrayTemp[i - 1].patientCode = appointmentsArrayTemp[i - 1].patientCode - 1;
 
    }
 
    delete[] appointmentsArray;
    appointmentsArray = appointmentsArrayTemp;
 
    RemovePatient(patientsArray, numberOfPatients, patientToDelete);
}
 
 
void Registry::ShowAllPatientAppointments(Registry *appointmentsArray, Patient *patientsArray, Doctor *doctorsArray,
                                          int numberOfPatients) {
 
    for (int i = 0; i < numberOfPatients; i++) {
        cout << endl;
        cout << "Номер пацієнта: " << patientsArray[appointmentsArray[i].patientCode].GetPatientCode() << endl;
        cout << "Ім'я пацієнта: " << patientsArray[appointmentsArray[i].patientCode].GetPatientName() << endl;
        cout << "Фамілія пацієнта: " << patientsArray[appointmentsArray[i].patientCode].GetPatientSurname() << endl;
        cout << "Вік пацієнта: " << patientsArray[appointmentsArray[i].patientCode].GetPatientAge() << endl;
        cout << "Номер телефону пацієнта: " << patientsArray[appointmentsArray[i].patientCode].GetPatientPhone()
             << endl;
        cout << endl;
 
        cout << "Назначений лікарь: " << endl;
        cout << "Ім'я лікаря: " << doctorsArray[appointmentsArray[i].doctorCode].GetDoctorName() << endl;
        cout << "Фамілія лікаря: " << doctorsArray[appointmentsArray[i].doctorCode].GetDoctorSurname() << endl;
        cout << "Кваліфікація лікаря: " << doctorsArray[appointmentsArray[i].doctorCode].GetDoctorQualification()
             << endl;
 
        cout << "Дата прийому: " << appointmentsArray[appointmentsArray[i].patientCode].date.day << "."
             << appointmentsArray[appointmentsArray[i].patientCode].date.month
             << "." << appointmentsArray[appointmentsArray[i].patientCode].date.year << endl;
 
 
    }
 
}
 
void Registry::ShowDoctorAppointments(Registry *appointmentsArray, Patient *patientsArray, Doctor *doctorsArray,
                                      int numberOfPatients, int numberOfDoctors) {
 
    cout << "Оберіть номер необхідного лікаря" << endl;
    for (int i = 0; i < numberOfDoctors; i++) {
        cout << "Номер лікаря: " << i << endl;
        cout << "Ім'я лікаря: " << doctorsArray[i].GetDoctorName() << endl;
        cout << "Фамілія лікаря: " << doctorsArray[i].GetDoctorSurname() << endl;
        cout << "Кваліфікація лікаря: " << doctorsArray[i].GetDoctorQualification() << endl;
        cout << endl;
 
    }
 
    cout << "➡ ";
    int choosedDoctor = 0;
    cin >> choosedDoctor;
    char c;
    while( (cin.get())!='\n' )
        ;
 
    for (int i = 0; i < numberOfPatients; i++) {
 
        if (doctorsArray[appointmentsArray[i].doctorCode].GetDoctorCode() == choosedDoctor) {
 
            cout << "Номер пацієнта: " << patientsArray[appointmentsArray[i].patientCode].GetPatientCode() << endl;
            cout << "Ім'я пацієнта: " << patientsArray[appointmentsArray[i].patientCode].GetPatientName()
                 << endl;
            cout << "Фамілія пацієнта: "
                 << patientsArray[appointmentsArray[i].patientCode].GetPatientSurname() << endl;
            cout << "Вік пацієнта: " << patientsArray[appointmentsArray[i].patientCode].GetPatientAge()
                 << endl;
            cout << "Номер телефону пацієнта: "
                 << patientsArray[appointmentsArray[i].patientCode].GetPatientPhone() << endl;
            cout << "Дата прийому: " << appointmentsArray[appointmentsArray[i].patientCode].date.day << "."
                 << appointmentsArray[appointmentsArray[i].patientCode].date.month
                 << "." << appointmentsArray[appointmentsArray[i].patientCode].date.year << endl;
            cout << endl;
        }
    }
}


Спасибо за ваш ответ, вроде стало лучше, и теперь не записывается только имя начиная со 2 пациента. Посмотрите пожалуйста, может я опять в чем то не понял и не дописал что-то.
0
Модератор
Эксперт С++
 Аватар для zss
13794 / 10986 / 6492
Регистрация: 18.12.2011
Сообщений: 29,287
16.09.2022, 10:36
Я этот код откомпилировать не могу. У меня VS 2008.
Воспользуйтесь отладчиком:
Как пользоваться отладчиком (в Visual Studio)
0
7 / 6 / 1
Регистрация: 04.10.2021
Сообщений: 268
16.09.2022, 11:22  [ТС]
zss, а что именно я должен буду увидеть в отладчике, лишние символы в строке?
0
Модератор
Эксперт С++
 Аватар для zss
13794 / 10986 / 6492
Регистрация: 18.12.2011
Сообщений: 29,287
16.09.2022, 13:08
Смотрите, что вводится и что записывается.
0
Надоела реклама? Зарегистрируйтесь и она исчезнет полностью.
raxper
Эксперт
30234 / 6612 / 1498
Регистрация: 28.12.2010
Сообщений: 21,154
Блог
16.09.2022, 13:08

Массив обьектов класса предка и производного
Можно ли, если у меня есть базовый НЕ абстрактный класс и проиводный от него с добавленым полем, допустим, целое число, сделать массив,...

Передать массив обьектов в метод класса
Здраствуйте господа программисты! Подскажите пожалуйста как передать массив обьектов в метод класса: #include &lt;conio.h&gt; ...

Как считать с файла в массив обьектов класса
Нужно считать с файла в строку потом эту строку разбить на фио знак зодиака и день рождения и занести в переменные те что находятся в...

Создать массив объектов класса, организовать поиск и записать в текстовый файл
Здравствуйте, нужно создать массив объектов класса, Вывести: 1 список студентов заданного факультета; 2 списки студентов для каждого...

Массив обьектов (для дальнейшей инициализации ) внутри класса
Добрый день, такой вопрос, как можно на питоне создать класс &quot;магазин&quot;, внутри которого будет находиться массив. После того как мы...


Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:
32
Ответ Создать тему
Новые блоги и статьи
GitHub Copilot в JetBrains: модель по умолчанию, Fix и контроль MCP
and_y87 12.10.2026
10 октября 2026 года GitHub обновил Copilot для JetBrains: добавил настройки стартовой модели, исправления из диагностики и управление автозапуском MCP. Поддержка IDE 2025. 1 прекращена — требуется. . .
День 5 из 28: Codex подсказывает следующий запрос
and_y87 12.10.2026
9 октября 2026 года OpenAI запустила бету Composer predictions — подсказок следующего сообщения в текущем диалоге Codex. Это помощь с формулировкой запроса, а не автоматическое продолжение задачи. . . .
Запустил конкурс "тем и промптов для текстовых квестов созданных почти чисто ИИ"
Adler 06.10.2026
Всем привет! За последние три-четыре дня я создал более 16 текстовых квестовых игр используя преимущественно по одному запросу к ИИ на игру. Мне так понравилось смотреть все ветки/ сцены во всех. . .
ИИ не может найти нужный язык в списке
Supersumestria 05.10.2026
Я ему даю вот такое изображение и прошу найти и подчеркнуть немецкий язык. Возвращает он вот это: https:/ / i. **********/ vqBWLe2. png Нужную строчку в 3й колонке просто выдумал. . Это. . .
Новая последняя моя музыка в SUNO
zorxor 05.10.2026
Здравствуйте, дорогие мои друзья! С большой радостью я хотел бы представить вам свою новую последнею музыку, которую сгенерировала мне по моей просьбе нейросеть SUNO. С уважением, zorxor. Это. . .
Программный домашний кинотеатр
russiannick 27.09.2026
Сподобился на программный домашний кинотеатр. В качестве ЯВУ по традиции выбрал js. В помощники взял Яндекс-Алису. Было создано три зала на разные интересы. исторические и ретро сериал Хичкок. . .
Беседа с ИИ о программистах, недопускающих к созданию и правке кода генеративные ИИ и причины этого
zorxor 21.09.2026
Раньше я радовался или получал некоторые эмоции, пусть небольшие, но всё же, от самого процесса написания кода, рекомпиляции и запуска, видя постепенное развитие программы и прочее. А теперь лень. . .
Мобильное приложение ColorStep
pavlinmavlin 17.09.2026
Реализовал приложение Красный, Зеленый, Синий в Unity3d + c#. Название изменил на ColorStep. Приложение прошло модерацию и теперь доступно для скачивания. Делал его сам, шаг за шагом — и вот,. . .
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2026, CyberForum.ru