我正在读取一个文本文件,该文件由名称和等级组成,格式为:
Polly 95 99 95 94 93 98 99
Abraham 80 85 81 86 95 78 81
我使用以下代码将每个学生读入Student_info结构:
// read homework grades from an input stream into a vector<double>
istream& read_hw(istream& in, vector<double>& hw)
{
if (in)
{
// get rid of previous content
hw.clear();
// read hw grades
double grade;
while (in >> grade) hw.push_back(grade);
// clear the stream so that input will work for next student
in.clear();
}
return in;
}
istream& read(istream& in, Student_info& s)
{
// read and store the student's name, midterm, and final
in >> s.name >> s.midterm >> s.final;
//std::cout << "The name is " << s.name << std::endl;
read_hw(in, s.homework);
return in;
}
稍后,我打印每个学生的姓名和总成绩,但是发生了一些奇怪的事情。而不是得到
Polly 96.6
Abraham 82.2
第一个(Polly)之后的每个名称都被部分切除:
Polly 96.6
raham 82.2
我相信这与清除流以便为下一个学生做好准备有关:
in.clear();
看来似乎已经舍弃了下一个学生名字的开头,但是我不能仅仅摆脱这一行,因为istream需要返回到OK状态。
我该如何完成这项任务,但要确保我不会丢掉每个学生名字的一部分?(我假设我可能事先不知道有多少作业,所以我不能简单地读6个双打然后继续。)
我该如何完成这项任务,但要确保我不会丢掉每个学生名字的一部分?
std::string line;
if (getline(in, line))
{
std::istringstream iss(line);
while (iss >> grade)
hw.push_back(grade);
}
这是一种更加结构化的方法,要求在当前行中列出数字。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句