私がしようとしているのは、名前、ID、結果、および成績に基づいてテキストファイルに学生の詳細を並べ替えることです。私は3番目のワードに基づいて昇順に私のテキストファイル内の行をソートするためにしようとしています(各単語がタブ「\ t」ので区切られている)3番目の単語に基づいてテキストファイルの行を並べ替えるにはどうすればよいですか?
rose ramzi 154ss6 85 A
john watson 123aq1 96 A+
ellen thomas qs2115 75 B+
:ここ
は次のように私のText_File.txt
が見えるものです(これは学生のIDです)。
私は最初の名前でリストを並べ替えることができました。また、3番目の単語を抽出してsort()
関数を使って試しましたが、まだ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;
}
私の目的は、自分のID番号に基づいて学生を並べ替えることです。
は、ここに私のsorting_by_id
コードです。
ありがとうございました。
あなたのコードはまさにあなたが期待している通りに書かれています。だから問題は何ですか?受講者IDの「123aq1、154ss6、qs2115」の順番は、実際には文字列の辞書順になっています。 – user202729
サイドノート:リテラルタブの文字を表すには、コードで ''\ t''を使用してください。 – user202729
substrのパラメータとして指定された長さが正しくありません。これは、(wordEndPositionX - wordStartPositionX -1)にする必要があります。あなたが与えているのは、実際には単語の最後の後に残っている行のサイズです。 –