本文共 2352 字,大约阅读时间需要 7 分钟。
真正的C++
(1)不提倡指针
(2)提倡数据抽象,提倡使用类
(3)提倡使用库
------<<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 杨小敏 652004103 李兵 76 2004104 周星华 602004105 王小青 822004106 陈江 702004107 刘慧姗 852004108 张真 802004109 林华 702004110 郭云风 62*/
注:代码参考CSDN博客,非本人原版.思想也是来自CSDN博客
转载地址:https://blog.csdn.net/iteye_18039/article/details/81971440 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!