Я новичок в 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. Это отключается как 'rpenter'. Не уверен, что моя проблема здесь. Кто-нибудь может помочь прояснить это?
#include <iostream>
#include <vector>
using std::istream;
using std::vector;
using std::string;
using std::endl;
using std::cout;
using std::max;
using std::cin;
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;
}
int main() {
vector<Student_info> students;
Student_info record;
string::size_type maxlen = 0;
//read and store all the records, and find the length of the longest name
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) {
// write the name, padded on the right to maxlen + 1 characters
cout << students[i].name << endl;
}
return 0;
}