您可以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 expressions(見Wikipedia)調用std::sort
時:
std::sort(std::begin(assignments), std::end(assignments),
[](const Assignment& a, const Assignment& b)
{
return a.Assignment_name < b.Assignment_name;
});
個
參考文獻:
使用'std :: sort'。 :v – rightfold
要存儲到類變量中的「價值」是什麼? – MadeOfAir
Assignment_type =「H」,Date =「2012/08/05」,Max_score =「20」,Actual_score =「13」,第一行Assignment_name =「作業1」 – nastalgia