Accelerated C++ 的练习 4-6 要求我编写一个程序来读取并计算学生的总成绩。我有以下代码:
// source file for Student_info-related functions
#include "Student_info.h"
#include "grade.h"
using std::istream; using std::vector;
using namespace std;
bool compare(const Student_info& x, const Student_info& y)
{
return x.name < y.name;
}
istream& read(istream& is, Student_info& s)
//void read(istream& is, Student_info& s)
{
double midterm, final;
// read and store the student's name and midterm and final exam grades
is >> s.name >> midterm >> final;
std::vector<double> homework;
read_hw(is, homework); // read and store all the student's homework grades
s.grade = grade(midterm, final, homework);
cout << "name is: " << s.name << endl;
/// cout << "midterm is: " << midterm << endl;
/// cout << "final is: " << final << endl;
cout << "grade is: " << s.grade << endl;
cout << "" << endl;
return is;
}
// read homework grades from an input stream into a 'vector<double>'
istream& read_hw(istream& in, vector<double>& hw)
{
cout << "I get into read_hw!" << endl;
if (in) {
// get rid of previous contents
hw.clear();
// read homework grades
double x;
while (in >> x)
hw.push_back(x);
// clear the stream so that input will work for the next student
in.clear();
}
cout << "I get (just before) out of read_hw!" << endl;
return in;
}
从 main() 调用上述内容:
int main()
{
vector<Student_info> students;
Student_info record;
string::size_type maxlen = 0; // the length of the longest name
// read and store all the students data.
// Invariant: students contains all the student records read so far
// maxlen contains the length of the longest name in students
while (read(cin, record)) {
cout << "Get into read() while loop" << endl;
// find length of longest name
maxlen = max(maxlen, record.name.size());
students.push_back(record);
cout << "Get to end of read() while loop" << endl;
}
cout << "I get out of read ok!!" << endl; // WE NEVER GET THIS FAR
这是输出:
(Canopy 32bit) joes-imac:4-6 david$ make test
./main <data/gradesTest
I get into read_hw!
I get (just before) out of read_hw!
name is: Moo
grade is: 100
Get into read() while loop
Get to end of read() while loop
I get into read_hw!
I get (just before) out of read_hw!
name is: Moore
grade is: 79.4
Get into read() while loop
Get to end of read() while loop
I get into read_hw!
I get (just before) out of read_hw!
name is: Norman
grade is: 72.8
Get into read() while loop
Get to end of read() while loop
I get into read_hw!
I get (just before) out of read_hw!
libc++abi.dylib: terminate called throwing an exception
/bin/sh: line 1: 20610 Abort trap: 6 ./main < data/gradesTest
make: *** [test] Error 134
(Canopy 32bit) joes-imac:4-6 david$
为什么会失败?为什么当程序失败(数据输入末尾没有空行或类似的东西)时,我们似乎进行了一次空白运行(即没有读入任何数据)?