Имеется класс student, данные, которого нужно записать в текстовый файл. Во время компиляции программы происходит бесконечная запись в файл, которая не прерывается. При этом записывается только один класс(name, age, kurs в единственном числе),хотя по условию задания количество "студентов" вводится с клавиатуры. Как следует исправить данные ошибки?
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
class student{
private:
string name;
int age;
int kurs;
public:
student(string name, int age, int kurs) {
this->name = name;
this->age = age;
this->kurs = kurs;
}
~student(){};
double get_age(){
return age;
}
int get_kurs(){
return kurs;
}
void print()
{
cout << "Name: " << name << endl;
cout << "age: " << age << endl;
cout << "kurs: " << kurs << endl << endl;
}
void key()
{
cin.ignore(INT_MAX, '\n');
cout << "Enter name: ";
cin >> name;
cout << "Age: ";
cin >> age;
cout << "Enter course: ";
cin >> kurs;
cout << endl;
}
};
int main() {
string namest;
int agest;
int kursst;
int number;
cout << "Enter the number of student: ";
cin >> number;
student stud(namest, agest, kursst);
ofstream file("file.txt",ios::out);
if (!file.is_open()){
cout<<"ошибка в открытии файла"<<endl;
}
else{
cout<<"файл открыт"<<endl;
for (int i=0;i<number;i++){
stud.key();
file.write((char*)&stud,sizeof(stud));
}
}
file.close();
ifstream infile("file.txt",ios::in);
cout << "файл открыт" << endl;
while (!infile.eof()) {
if (stud.get_kurs() == course) {
all_age += stud.get_age();
counter++;
}
}
cout << "Average age is about: " << all_age / counter << endl;
file.close();
return 0;
}
while (!infile.eof())— так нельзя, см. https://ru.stackoverflow.com/q/833980/195342 – Harry Sep 24 '21 at 04:16