如何根据第三个单词对文本文件中的行进行排序? [英] How can I sort lines in a text file based on the third word?
问题描述
我要做的是根据学生的名字,身份证,成绩和成绩在文本文件中对他们的详细信息进行排序.
What I am trying to do is sort the students' details in a text file based on their first name, id, results and grades.
这是我的Text_File.txt
的样子:(每个单词用制表符'\ t'分隔)
Here is what my Text_File.txt
looks like: (each word is separated by tab '\t')
rose ramzi 154ss6 85 A
john watson 123aq1 96 A+
ellen thomas qs2115 75 B+
我正在尝试根据第三个单词(这是学生的ID)以升序对文本文件中的行进行排序.
I am trying to sort the lines in my text file in ascending order based on the third word (which is the student's ID).
我可以使用名字对列表进行排序,还可以提取第三个单词并尝试使用sort()
函数,但是仍然无法按ID进行排序.
I was able to sort the list with the first name and also I could extract the third word and tried using sort()
function but it is still not sorting by ID.
这是我的sorting_by_id
代码:
int main() {
fstream input("Text_File.txt", ios::in | ios::out);
string line;
vector<string> lines;
while (getline(input, line))
lines.push_back(line);
sort(lines.begin(), lines.end(), [](const string& a, const string& b) {
int wordStartPositionA = 0, wordStartPositionB = 0;//The start of each word in the string
for (int i = 0; i < 2; i++)//looking for the third word in 1st sentence
wordStartPositionA = a.find_first_of(' ', wordStartPositionA + 1);
for (int i = 0; i < 2; i++)//looking for the third word in 2nd sentence
wordStartPositionB = b.find_first_of(' ', wordStartPositionB + 1);
//Getting where our word ends:
int wordEndPositionA = a.find_first_of(' ', wordStartPositionA + 1);
int wordEndPositionB = b.find_first_of(' ', wordStartPositionB + 1);
//Getting the desired word
string resultA = a.substr(wordStartPositionA + 1, a.length() - wordEndPositionA - 1);
string resultB = b.substr(wordStartPositionB + 1, b.length() - wordEndPositionB - 1);
//cout << resultA << " " << resultB << endl;
return resultA < resultB;
});
for_each(lines.begin(), lines.end(), [](const string& s) {
cout << s << endl; });
getchar();
return 0;
}
我的目的是根据学生的身份证号对他们进行排序.
My aim is to sort the students based on their ID number.
谢谢您的帮助:)
推荐答案
您需要一些数据抽象.
首先定义合适的数据类型:
First define a suitable data type:
struct Student
{
std::string firstName;
std::string lastName;
std::string id;
int result;
std::string grade;
};
然后,您定义如何读取其中之一:
then you define how to read one of them:
std::istream& operator>>(std::istream& is, Student& s)
{
return is >> s.firstName >> s.lastName >> s.id >> s.result >> s.grade;
}
然后您阅读它们:
int main()
{
std::ifstream input("Text_File.txt");
std::vector<Student> students;
Student s;
while (input >> s)
{
students.push_back(s);
}
然后您可以轻松按ID对它们进行排序:
then you can easily sort them by id:
std::sort(students.begin(),
students.end(),
[](const Student& s1, const Student& s2) { return s1.id < s2.id; });
或减少结果:
std::sort(students.begin(),
students.end(),
[](const Student& s1, const Student& s2) { return s1.result > s2.result; });
或其他任何方式.
这篇关于如何根据第三个单词对文本文件中的行进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!