Tygawr -12 Newbie Poster

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);
	}
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.