目录
一、前言
在实际的编程应用中,我们常常需要从文件中读取数据,对这些数据进行处理,例如排序,然后可能会将处理后的数据写回到文件或者进行其他操作。本文将详细介绍如何使用 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 ;