C++匹配.txt文件中特定字符,并输出所在行内容

本文参考了下面两篇文章:

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文件:

 以上代码基于他人成果上整理得出,尚有不足之处,还需修改完善。

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值