本文参考了下面两篇文章:
https://blog.csdn.net/AAADiao/article/details/131594975
【C++】读取txt文件中指定行的内容_c++读取txt指定行_只搬烫手的砖的博客-CSDN博客
c++代码如下:
#include <iostream>
#include <fstream>
#include <string>
#include <assert.h>
#include <vector>
using namespace std;
//获得txt行数
int CountLines(string filename)
{
ifstream ReadFile;
int n = 0;
string tmp;
ReadFile.open(filename.c_str()); //ios::in 表示以只读的方式读取文件
if (ReadFile.fail()) //文件打开失败:返回0
{
return 0;
}
else//文件存在
{
while (getline(ReadFile, tmp, '\n'))
{
n++;
}
ReadFile.close();
return n;
}
}
//读取某行数据
string ReadLine(string filename, int line)
{
int lines, i = 0;
string temp;
fstream file;
file.open(filename.c_str());
lines = CountLines(filename);
if (line <= 0)
{
return "Error 1: 行数错误,不能为0或负数。";
}
if (file.fail())
{
return "Error 2: 文件不存在。";
}
if (line > lines)
{
return "Error 3: 行数超出文件长度。";
}
while (getline(file, temp) && i < line - 1)
{
i++;
}
file.close();
return temp;
}
void CompareFileFileds(string filePath, string compareFileds)
{
fstream fs;
fs.open(filePath);
if (fs.fail())
{
fs.close();
cout << "fstream fail!" << endl;
}
int i = 1;
int lines = CountLines(filePath);
string fileString;
while (getline(fs, fileString) && i < lines) //遍历所有行
{
int index = fileString.find(compareFileds, 1); //匹配到字符,返回值为1
if (index > 0)
{
string tmp = ReadLine(filePath, i); //返回字符所在行的内容
cout << tmp << endl;
}
i++;
}
cout << "not find compareFileds!" << endl;
}
int main() {
printf("输入卫星编号:"); //输入需要匹配的字符
string compareFileds;
cin >> compareFileds;
CompareFileFileds(".\\a.txt", compareFileds);
}
运行结果:
a.txt文件:
以上代码基于他人成果上整理得出,尚有不足之处,还需修改完善。