2017-12-04 5 views
-1

私がしようとしているのは、名前、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コードです。

ありがとうございました。

+0

あなたのコードはまさにあなたが期待している通りに書かれています。だから問題は何ですか?受講者IDの「123aq1、154ss6、qs2115」の順番は、実際には文字列の辞書順になっています。 – user202729

+0

サイドノート:リテラルタブの文字を表すには、コードで ''\ t''を使用してください。 – user202729

+0

substrのパラメータとして指定された長さが正しくありません。これは、(wordEndPositionX - wordStartPositionX -1)にする必要があります。あなたが与えているのは、実際には単語の最後の後に残っている行のサイズです。 –

答えて

2

データの抽象化が必要です。

まず、適切なデータ型を定義:

std::istream& operator>>(std::istream& is, Student& s) 
{ 
    return is >> s.firstName >> s.lastName >> s.id >> s.result >> s.grade; 
} 

その後、あなたがそれらを読む:あなたはそれらのいずれかを読み取る方法を定義

struct Student 
{ 
    std::string firstName; 
    std::string lastName; 
    std::string id; 
    int result; 
    std::string grade; 
}; 

int main() 
{ 
    std::ifstream input("Text_File.txt"); 
    std::vector<Student> students; 
    Student s; 
    while (input >> s) 
    { 
     students.push_back(s); 
    } 

、あなたをすることができますIDで簡単に並べ替える:

または減少結果によって:

std::sort(students.begin(), 
      students.end(), 
      [](const Student& s1, const Student& s2) { return s1.result > s2.result; }); 

または何によって

+0

それは働いた!あなたの時間と助けてくれてありがとう! :) –

+0

いいえ 'std :: copy(std :: istream_iterator {input}、{}、std :: back_inserter {students});'? – Caleth

関連する問題