Hi all,
I am trying to figure out the code for searching a text file for a word/phrase and then replacing it. Both are user-input values. I've been having a tough time finding some help online because we are required to use get and put, not strings, unfortunately. The controllers we will eventually be programming will require us to know get/put and the other iostream functions well.

My thought process is this:
For a search term of "the end" to be replaced by "bye bye"
1. My program needs to save "the end" as an array, search[], and "bye bye" as an array, replace[].
2. Search the text file using a while loop and get for the array search.
3. Using an if statement identify any arrays of the same content as search.
4. Use put to replace the found array with replace.

Here is the code for my function so far. It feels way too simple, for what I described above, but I'm not sure what else to try. Any help, useful links, or edits are greatly appreciated.

void replaceText(ifstream& fileIn, ofstream& fileOut, char *search, char *replace)
{
	char i;

	while (fileIn.get() != EOF) 
	{
	if (i == *search)
		fileOut.put(*replace);
	}
}

Recommended Answers

All 2 Replies

Maybe something along these lines, although I'm not sure if it really works.
Probably the loop is wrong and will skip the last character...

But you have something to work with :)

const int len=sizeof(search);
char* tmp=new char[len];
int i=0;
while(const int len=sizeof(search)
char* tmp=new char[len]
int i=0;
while(!fileIn.get(&tmp[i]).eof()){
	if(tmp[i]!=search[i])
		i=0
	else if(i==len-1)
		//	output replace
		//	i=0
}

Thanks jaskij, I'll give it a shot. :-)

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.