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

本文介绍了一个使用C++读取文本文件中的学生数据,并按成绩排序输出到终端和文件的示例程序。通过定义Student类及重载比较运算符,利用STL容器和算法实现了高效的数据处理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

真正的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 杨小敏 65
2004103 李兵 76
2004104 周星华 60
2004105 王小青 82
2004106 陈江 70
2004107 刘慧姗 85
2004108 张真 80
2004109 林华 70
2004110 郭云风 62

*/

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值