(C++)读取一个txt文件,然后排序
前几天去面试的一道题:有一个TXT文件,包含三个字段,ID, Name, Salary,要求读入此文件帮其排序。由于是Linux环境所以用C++做这个题。

#include<iostream>
#include<fstream>
#include<string>
#include<vector>
using namespace std;
//keep one employee info
typedef struct em
{
int id;
string name;
int salary;
}
Employee;
//keep the table title
static string title;
//Read the data from file to the vector
vector<Employee> ReadData(string path)
{
string t1,t2,t3;
ifstream fIn(path);
fIn>>t1;
fIn>>t2;
fIn>>t3;
title=t1+" "+t2+" "+t3;
vector<Employee> empSet;
while(fIn.peek()!=EOF)
{
Employee e;
fIn>>e.id;
fIn>>e.name;
fIn>>e.salary;
empSet.push_back(e);
}
fIn.close();
return empSet;
}
//Print the vector text to console
void PrintData(vector<Employee> empSet)
{
cout<<title<<endl;
for(int i=0;i<empSet.size();i++)
{
cout<<empSet[i].id<<" "<<empSet[i].name<<" "<<empSet[i].salary<<endl;
}
}
//sort by salary
vector<Employee> Sort(vector<Employee> empSet)
{
for(int i=0;i<empSet.size()-1;i++)
{
for(int j=i+1;j<empSet.size();j++)
{
if(empSet[i].salary>empSet[j].salary)
{
Employee temp;
temp=empSet[i];
empSet[i]=empSet[j];
empSet[j]=temp;
}
}
}
return empSet;
}
int main(int argc, char**argv)
{
vector<Employee> orginalData=ReadData("salary.txt");
cout<<"Orginal Data:"<<endl;
PrintData(orginalData);
vector<Employee> SortedData=Sort(orginalData);
cout<<"Sorted Data:"<<endl;
PrintData(SortedData);
getchar();
}
#include<fstream>
#include<string>
#include<vector>
using namespace std;
//keep one employee info
typedef struct em
{
int id;
string name;
int salary;
}
Employee;
//keep the table title
static string title;
//Read the data from file to the vector
vector<Employee> ReadData(string path)
{
string t1,t2,t3;
ifstream fIn(path);
fIn>>t1;
fIn>>t2;
fIn>>t3;
title=t1+" "+t2+" "+t3;
vector<Employee> empSet;
while(fIn.peek()!=EOF)
{
Employee e;
fIn>>e.id;
fIn>>e.name;
fIn>>e.salary;
empSet.push_back(e);
}
fIn.close();
return empSet;
}
//Print the vector text to console
void PrintData(vector<Employee> empSet)
{
cout<<title<<endl;
for(int i=0;i<empSet.size();i++)
{
cout<<empSet[i].id<<" "<<empSet[i].name<<" "<<empSet[i].salary<<endl;
}
}
//sort by salary
vector<Employee> Sort(vector<Employee> empSet)
{
for(int i=0;i<empSet.size()-1;i++)
{
for(int j=i+1;j<empSet.size();j++)
{
if(empSet[i].salary>empSet[j].salary)
{
Employee temp;
temp=empSet[i];
empSet[i]=empSet[j];
empSet[j]=temp;
}
}
}
return empSet;
}
int main(int argc, char**argv)
{
vector<Employee> orginalData=ReadData("salary.txt");
cout<<"Orginal Data:"<<endl;
PrintData(orginalData);
vector<Employee> SortedData=Sort(orginalData);
cout<<"Sorted Data:"<<endl;
PrintData(SortedData);
getchar();
}
由于太久没有用C++了,所以当时没有做出来很郁闷,回来后就开始做这个题。输出结果:
posted on 2010-01-25 15:20 Jeff Leung 阅读(1349) 评论(0) 收藏 举报