I've seen other people reporting this problem with cin.ignore()
and getline()
. I understand it's some problem involving newlines, but I'm not entirely sure how to debug this with >>. I'm trying to implement a gradebook that takes in a student name and test grades and outputs their name (and eventually, course grade) [from Chapter 4 of Accelerated C++]. I'm having trouble even outputting the names properly, though.
// Student.cpp
#include "Student.h"
#include <iostream>
#include <vector>
istream& read(istream& in, Student& s) {
in >> s.name >> s.midterm;
read_hw(in, s.homework);
return in;
}
istream& read_hw(istream& in, vector<double>& hw) {
if (in) {
hw.clear();
double x;
while (in >> x)
hw.push_back(x);
in.clear();
}
return in;
}
And here I try to test it with my main function:
int main() {
vector<Student> students;
Student curr_student;
while (read(cin, curr_student)) {
cout << curr_student.name;
students.push_back(curr_student);
cout << students.size() << endl;
}
cout << students.size() << endl;
for (int i = 0; i < students.size(); i++) {
cout << students[i].name << endl;
}
return 0;
}
When I input something into the command line, though, the output of the student names after the first one are cut off:
Input in terminal:
Alice 50 50 50 50 (<enter>)
Bob 100 100 100 100 (<enter>)
Carl 50 50 50 50 (<enter>)
(<Ctrl-D>)
And then it outputs:
Alice
ob
rl