struct Student_info {
std::string name;
double midterm,final;
std::vector<double> homework;
};
I am writing a C++ program from Accelerated C++ that uses the above struct to define an individual student. The goal is to store and calculate the grades for multiple students. The program should take input from stdin in the form of a name, two test scores, and then some unknown number of homework grades. These values all get loaded into a struct, and then the struct gets added to the vector of Student_info. The code to do this is below.
int main(){
std::vector<Student_info> students;
Student_info record;
std::string::size_type maxlen = 0;
while(read(std::cin,record)){
maxlen = std::max(maxlen,record.name.size());
students.push_back(record);
}
}
std::istream& read(std::istream& is, Student_info& student){
std::cout << "Enter your name, midterm, and final grade: ";
is >> student.name >> student.midterm >> student.final;
std::cout << student.name << " "<< student.midterm << " " << student.final;
read_hw(is,student.homework);
return is;
}
std::istream& read_hw(std::istream& in,std::vector<double>& hw){
if(in){
hw.clear();
double x;
while(in>>x){
hw.push_back(x);
}
in.clear();
in.ignore(std::numeric_limits<std::streamsize>::max());
}
return in;
}
However the input is not reading correctly. Input of
Sam 90 88 90 88 89 \eof Jack 86 84 85 80 82 \eof
Gives:
student.name = Sam
student.midterm = 90.
student.final = 88.
student.homework = [90,88,89]
student.name = \eof
student.midterm = 0
student.final = 88
student.homework
This last student does not fit the struct so the read fails and the while loop ends, and Jack never gets added to the vector.
in
read_hw
you are readinghomework
until stream is closed.The first
\eof
char closes standard input for good.=> other students cannot be entered from a closed input stream.
You have to find another way to end
homework
input, like for instance an empty line.