麻雀虽小五脏俱全 现代C++思想 值得推敲

真正的C++

(1)不提倡指针

(2)提倡数据抽象,提倡使用类

(3)提倡使用库

------<<C++沉思录>>

本文中问题的解决很好的体现了以上几点,如果不想学习C++误入歧途,陷入方言.请仔细研读本程序的实现思路,虽然它不是本人原创.

// 问题条件:文本文件中有如下学生数据

麻雀虽小五脏俱全 现代C++思想 值得推敲

// 要求:对文本中的数据按成绩排序,之后输出到result.txt文件中,同时显示结果

// 解决思路:将文件中的数据读入到vector对象vectStu中进行排序,vector必须盛放一行数据.

//创建student类,用其对象作为vector的元素.每次从文件中读一行到string的临时对象line中.

//用string流对象从line中读取此行的三个数据(学号,姓名,分数)到三个临时变量中.

//用这三个临时对象初始化一个student对象,将这个初始化的对象放入vectStu中.

//为利用sort对vectStu排序,需要student类支持operator<操作符重载.

//最后将vectStu的内容输出到终端,输出到文件.此时对vectStu中的每个student,为获取其私有

//成员,要求student类提供只读接口.

//完整实现

#include <iostream>
#include <fstream>
//#include <cstdlib>
//#include <cstdio>
#include <string>
#include <sstream>
#include <vector>
#include <algorithm>

using namespace std;

class Student
{
public:
Student();
Student ( string Number, string Name, int Score ): number( Number ), name( Name ), score( Score ){}
~Student (){};

int getScore() const{
return score;
}

string getNumber() const{
return number;
}

string getName() const{
return name;
}

bool operator<( const Student &Stu ) const{
return score < Stu.getScore();
}
private:
/* data */
string number;
string name;
int score;
};

void PrintVec( vector< Student > &vec ){
int i = 0;
for(vector<Student>::size_type i = 0; i < vec.size(); i ++ )
{
Student stu = vec[i];
cout<<"Number:"<<stu.getNumber()<<" "<<"Name:"<<stu.getName()<<" "<<"Score:"<<stu.getScore()<<endl;
}
}

void WriteResult( vector< Student > &vec ){
ofstream fout("result.txt");

int i = 0;
for(vector<Student>::size_type i = 0; i < vec.size(); i ++ )
{
Student stu = vec[i];
fout<<stu.getNumber()<<" "<<stu.getName()<<" "<<stu.getScore()<<"/n";
}

fout.close();
}

int main (int argc, char const* argv[])
{
ifstream fin("test.txt");

vector< Student > students;
string lineIterm("");
string num;
string name;
int score;

while( getline( fin, lineIterm ) ){
//cout<<lineIterm<<endl;

//以空格来分隔string
istringstream iss( lineIterm );

iss>>num;
iss>>name;
iss>>score;
Student stu( num, name, score );

students.push_back( stu );
}


PrintVec( students );
cout<<"begin sort......."<<endl;
sort( students.begin(), students.end() );
cout<<"end sort........."<<endl;
PrintVec( students );
fin.close();

WriteResult( students );

return 0;
}

/*

2004101 张大志 89
2004102 杨小敏 65
2004103 李兵 76
2004104 周星华 60
2004105 王小青 82
2004106 陈江 70
2004107 刘慧姗 85
2004108 张真 80
2004109 林华 70
2004110 郭云风 62

*/

麻雀虽小五脏俱全 现代C++思想 值得推敲

麻雀虽小五脏俱全 现代C++思想 值得推敲

注:代码参考CSDN博客,非本人原版.思想也是来自CSDN博客