您可以使用std::getline
和std::istringstream
以及其他一些标准库功能来做到这一点:
class Assignment
{
// ...
public:
friend std::istream& operator>>(std::istream& is, Assignment& assignment)
{
std::string line;
std::getline(is, line);
std::istringstream iss(line);
iss >> assignment.Assignment_type;
iss >> assignment.Date;
iss >> assignment.Max_score;
iss >> assignment.Actual_score;
// The last field is a little difficult, as it should get the rest
// of the line, which can include spaces, and the `>>` operator
// separates on spaces
// Get the rest using `getline`
std::getline(iss, assignment.Assignment_name);
return is;
}
};
现在你可以做例如
std::ifstream input_file("data.txt");
Assignment assignment;
input_file >> assignment;
参考:
对于另一部分,您应该将新读取的Assigment
对象放在一个集合中,例如std::vector
. 然后,您可以根据std::sort
需要对它们进行排序:
std::vector<Assignment> assignments;
std::ifstream input_file("data.txt");
Assignment assignment;
while (input_file >> assignment)
assignments.push_back(assignment);
std::sort(std::begin(assignments), std::end(assignments));
要使该功能正常工作,您必须为您的作业std::sort
实现一个:operator<
class Assignment
{
// ...
public:
friend bool operator<(const Assignment& a, const Assignment& b)
{
return a.Assignment_name < b.Assignment_name;
}
};
如果您有 C++11(或更好)兼容的编译器,那么您可以在调用时使用lambda 表达式(另见Wikipediastd::sort
) :
std::sort(std::begin(assignments), std::end(assignments),
[](const Assignment& a, const Assignment& b)
{
return a.Assignment_name < b.Assignment_name;
});
参考: