从文本文件里读取信息,然后对里面的数据进行排序

目录

一、前言        

二、实现思路

三、代码示例

四、总结

参考:


一、前言        

        在实际的编程应用中,我们常常需要从文件中读取数据,对这些数据进行处理,例如排序,然后可能会将处理后的数据写回到文件或者进行其他操作。本文将详细介绍如何使用 C++ 从文本文件中读取信息,并对其中的数据进行排序。

二、实现思路

  • 文件读取:使用 C++ 的文件流对象 ifstream 打开文本文件,并逐行读取文件内容。
  • 数据存储:将读取到的数据存储到合适的数据结构中,这里我们选择使用 std::vector。
  • 数据排序:使用 std::sort 函数对存储的数据进行排序。
  • 结果输出:将排序后的数据输出到控制台或者写回到另一个文件中。

三、代码示例

#include <fstream>

#include <iostream>

#include <vecotr>

#include <algorithm>



#define MAXLINE 1024

using namespace std;



typedef struct employeeInfo

{

    string id = "";

    string name = "";

    int salary = 0;

}EmployeeInfo ;


EmployeeInfo* pEmployeeInfo = NULL; 

void writeFile(char* fName,char* rhsStr)

{

    ofstream file(fName); //./test20100120.txt");

    file << "hello world" ;

    file.close();



}


string readFile(const char* fName,vector<EmployeeInfo*> structEmployeeInfo ) 

{

    string Str ="" ;

    string tmpChar = "";



    ifstream file(fName);

    while( !file.eof() )

    {

        file >> tmpChar;                 

        Str += tmpChar + " ";

               tmpChar = ""; 

    }

    return Str ;

}


int main(int argc ,char** argv)

{

    string tmpFileName = "fileNameDemo.txt" ;

    const char* fName = tmpFileName.c_str() ; 

    //writeFile(fName,fName);


    vector<EmployeeInfo*> structEmployeeInfo ;

    readFile(fName,structEmployeeInfo);


    return 0;


}



#include <fstream>

#include <iostream>

#include <vector>

#include <algorithm>


#define MAXLINE 1024


using namespace std;


typedef struct employeeInfo

{

    string id ;

    string name;

    string salary ;



}EmployeeInfo ;



EmployeeInfo* pEmployeeInfo = NULL; 


void writeFile(char* fName,char* rhsStr)

{

    ofstream file(fName); //./test20100120.txt");

    file << "hello world" ;

    file.close();



}


void readFile(const char* fName,vector<EmployeeInfo>& vEmployeeInfo ) 

{

    string Str ="" ;

    string tmpChar = "";

    EmployeeInfo tmpEmployeeInfo ;



    ifstream file(fName);

    while( !file.eof() )

    {

        file >> tmpChar;                 

    tmpEmployeeInfo.id = tmpChar ;



        file >> tmpChar;                 

    tmpEmployeeInfo.name = tmpChar ;



        file >> tmpChar;                 

    tmpEmployeeInfo.salary = tmpChar ;

 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

大王算法

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值