Note: read the comments before replying. The problem seems to be specific to the compiler.
I have a simple program that reads the name and some grades from a file or console into the Student_info structure, and then prints some data, overloading the <and → operators. However, the program disables parts or even whole words and transfers data. For example, input
Eunice 29 87 42 33 18 13 Mary 71 24 3 96 70 14 Carl 61 12 10 44 82 36 Debbie 25 42 53 63 34 95
returns
Eunice: 42 33 18 13 Mary: 3 96 70 14 rl: 10 44 82 36 25: 63 34 95
assuming that somehow the stream ignored Karl's first two letters, and then moved the entire stream, leaving 1 word. I tried to debug this for most of the hour, but it seems arbitrary. For different names, different words are cropped without a visible picture.
#include <iostream> #include <fstream> #include <string> #include <vector> struct Student_info { friend std::ostream &operator<<( std::ostream &output, const Student_info &S ) { // overloads operator to print name and grades output << S.name << ": "; for (auto it = S.homework.begin(); it != S.homework.end(); ++it) std::cout << *it << ' '; return output; } friend std::istream &operator>>( std::istream &input, Student_info &S ) { // overloads operator to read into Student_info object input >> S.name >> S.midterm >> S.final; double x; if (input) { S.homework.clear(); while (input >> x) { S.homework.push_back(x); } input.clear(); } return input; } std::string name; // student name double midterm, final; // student exam scores std::vector<double> homework; // student homework total score (mean or median) }; int main() { //std::ifstream myfile ("/Users/.../Documents/C++/example_short.txt"); Student_info student; // temp object for receiving data from istream std::vector<Student_info> student_list; // list of students and their test grades while (std::cin >> student) { // or myfile >> student student_list.push_back(student); student.homework.clear(); } for (auto it = student_list.begin(); it != student_list.end(); ++it) { std::cout << *it << '\n'; } return 0; }
edit: added a newline character.
As you can see, it does not work with clang , but it works with GCC
source share