[C++] Read txt files and query specified fields

1. Function description

Function name illustrate
1 CompareFileFileds() Read the txt file by character or line, and then use string::find()the function to find the specified field. If it is found, it will return 0, if it is not found, it will return -1.

2. Code

Method 1. Use the "<<" operator

Description: Reading characters will stop when encountering a space.

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int CompareFileFileds(string filePath, string compareFileds)
{
    
    
	fstream fs;
	fs.open(filePath);
	if (fs.fail())
	{
    
    
		fs.close();
		cout << "fstream fail!" << endl;
		return -1;
	}

	string fileString;
	while (fs >> fileString)   //读取字符直到遇到空格
	{
    
    
		int index = fileString.find(compareFileds, 1);
		if (index > 0)
		{
    
    
			cout << "compare fileds index : " << index << endl;
			return 0;
		}
	}

	cout << "not find compareFileds!" << endl;
	return -1;
}

int main()
{
    
    
	string filePath = "C:\\Users\\ad\\Desktop\\file1.txt";
	string compareFileds = "ABC";
	int ret = CompareFileFileds(filePath, compareFileds);
	if (ret == 0)
	{
    
    
		cout << "Compare sucess!" << endl;
	}
	else
	{
    
    
		cout << "Compare fail!" << endl;
	}

	system("pause");
	return 0;
}

Method 2. Use string::getline()

Note: Read by line, even if there are spaces in a line, all can be read.

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int CompareFileFileds(string filePath, string compareFileds)
{
    
    
	fstream fs;
	fs.open(filePath);
	if (fs.fail())
	{
    
    
		fs.close();
		cout << "fstream fail!" << endl;
		return -1;
	}

	string fileString;
	while (getline(fs,fileString))  //读取一行
	{
    
    
		int index = fileString.find(compareFileds, 1);
		if (index > 0)
		{
    
    
			cout << "compare fileds index : " << index << endl;
			return 0;
		}
	}

	cout << "not find compareFileds!" << endl;
	return -1;
}

int main()
{
    
    
	string filePath = "C:\\Users\\ad\\Desktop\\file1.txt";
	string compareFileds = "ABC";
	int ret = CompareFileFileds(filePath, compareFileds);
	if (ret == 0)
	{
    
    
		cout << "Compare sucess!" << endl;
	}
	else
	{
    
    
		cout << "Compare fail!" << endl;
	}

	system("pause");
	return 0;
}

If this article is helpful to you, I would like to receive a like from you!

Insert image description here

Guess you like

Origin blog.csdn.net/AAADiao/article/details/131594975