1,105,625 Community Members

Tygawr's Find String In Text File Function

Member Avatar
Tygawr
Newbie Poster
24 posts since Mar 2012
Reputation Points: -12 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
0
 

OOPS! SORRY WRONG SECTION, I WANTED TO POST IN THE C++ SNIPPETS..

This piece of code will search for a string in a text file and write the results into another file along with the line number.

void IOSearchString()
{
	string SearchString, InputFilePath, OutputFilePath, InputFileLine;

	cout << "Welcome!" << endl
		 << "Please enter a string you wish to find:" << endl;
	cin >> SearchString;

	cout << endl << "Please enter the input file's path and name" << endl
		 << "(e.g c://InputFilePath//InputFileName.txt)" << endl;
	cin >> InputFilePath;

	ifstream InputFile(InputFilePath);
	if(!InputFile.is_open() || InputFile.bad())
	{
		cout << endl << "Error! Failed to open: " + InputFilePath << endl;
		system("Pause");
		exit(1);
	}

	cout << endl << "Please enter the output file's path and name:" << endl;
	cin >> OutputFilePath;

	ofstream OutputFile(OutputFilePath);
	if(!OutputFile.is_open() || OutputFile.bad())
	{
		cout << endl << "Error! Failed to create/find: " + OutputFilePath << endl;
		system("Pause");
		exit(1);
	}

	if(InputFile.good() && OutputFile.good())
	{
		int CountFound = 0;
		cout << endl << "Searching for: " + SearchString << endl;
		for(int LineCount = 1; getline(InputFile, InputFileLine); ++LineCount)
		{
			for(int i = 0; i != InputFileLine.length(); ++i)
			{
				if(InputFileLine.substr(i, SearchString.length()) == SearchString)
				{
					OutputFile << "Line " << LineCount << ":" << InputFileLine << endl;
					i = InputFileLine.length() - InputFileLine.substr(i, SearchString.length()).length();
					++CountFound;
				}
			}
		}
		cout << endl << "Searching completed!" << endl;

		if(CountFound <= 0)
		{
			cout << "Found: 0" << endl;
		}
		else if(CountFound > 0)
		{
			cout << "Found: " << CountFound << endl;
		}
	}
	else
	{
		cout << endl << "Error! Stream is not good for i/o operations!" << endl;
		system("Pause");
		exit(1);
	}

	InputFile.close();
	OutputFile.close();

	string YesNo;
	cout << endl << "Would you like to make a new search?" << endl
		 << "(Y = Yes | N = No)" << endl;
	cin >> YesNo;
	if(YesNo == "Y" || YesNo == "y")
	{
		system("cls");
		IOSearchString();
	}
	else
	{
		exit(0);
	}
}
You
This article has been dead for over three months: Start a new discussion instead
Post:
Start New Discussion
Tags Related to this Article