我是C ++的新手,我遇到了从标准输入读取多种类型的问题。我正在尝试输入诸如:
Smith 93 91 47 90 92 73 100 87
Carpenter 75 90 87 92 93 60 0 98
并且针对每一行提取不同的字段,并将它们存储为结构和向量。运行main.cpp后,我得到的输出是:
Smith
rpenter
未将完整字符串'Carpenter'完全读入Student_info.name。它被切断为“木匠”。不知道我的问题在这里。谁能帮忙解决这个问题?
struct Student_info {
std::string name;
double midterm, final;
std::vector<double> homework;
};
// 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 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();
}
return in;
}
istream& read(istream& is, Student_info& s) {
// read and store the student's name and midterm and final exam grades
is >> s.name >> s.midterm >> s.final;
read_hw(is, s.homework); // read and store all the student's homework grades
return is;
}
main.cpp
int main() {
vector<Student_info> students;
Student_info record;
string::size_type maxlen = 0;
while(read(cin, record)) {
maxlen = max(maxlen, record.name.size());
students.push_back(record);
}
for(vector<Student_info>::size_type i = 0; i != students.size(); ++i) {
cout << students[i].name << endl;
}
return 0;
}
用此替换read_hw()
函数中的while循环:
while (in.peek() != '\n' && in >> x) {
hw.push_back(x);
}
但是请注意,您必须在单独的行中输入每个学生记录。