[英]Issues reading multiple types from standard input
我是 c++ 的新手,我遇到了从标准输入读取多种类型的问题。 我正在尝试输入,例如:
Smith 93 91 47 90 92 73 100 87
Carpenter 75 90 87 92 93 60 0 98
并为每一行提取不同的字段并将它们存储到一个结构和一个向量中。 运行 main.cpp 后,我得到的 output 是:
Smith
rpenter
未将完整字符串“Carpenter”完全读入 Student_info.name。 它被切断为'renter'。 不知道我的问题在这里。 任何人都可以帮助解决这个问题吗?
#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;
}
将read_hw()
function 中的 while 循环替换为:
while (in.peek() != '\n' && in >> x) {
hw.push_back(x);
}
但请注意,您必须在单独的行中输入每个学生记录。 此外,在阅读该特定学生记录的最后作业成绩后,用户不应输入任何其他字符,而应输入'\n'
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.