This is the complete working code :
Code: C++
#include <iostream>
#include <algorithm>
#include <fstream>
#include <vector>
using namespace std;
struct StuRec
{
string Name;
short grades;
};
bool StuRecCompare (StuRec i,StuRec j)
{
return ( i.grades < j.grades );
}
int main()
{
vector<StuRec> Data;
StuRec TStudent;
Data.clear();
ifstream fin("C:\\TestData.txt");
while ( ! fin.eof() )
{
fin >> TStudent.Name;
fin >> TStudent.grades;
Data.push_back( TStudent );
}
fin.close();
sort(Data.begin(), Data.end(), StuRecCompare);
ofstream fout("C:\\SortedData.txt");
for (int i = 0; i < Data.size(); ++i)
{
fout << Data[i].Name << " ";
fout << Data[i].grades << endl;
}
fout.close();
return 0;
}
Brief explanation :
(1) You create a struct StuRec to store the records.
(2) You define your own func that compares two StuRecs.
(3) You create a StuRec vector and fill it up from the file "C:\\TestData.txt". (Change it as per your need.)
(4) You use STL sort to sort the vector according your comparison func.
(5) You write the data to a new file "C:\\SortedData.txt". (Change it as per your need.)