Hey
I have to write a program that will input the name of the text to be edited , name of the file that will hold the edited text, the data to be replaced (data1) and the new data which will replace the old (data2).All occurrences of the data1 to be changed on each line should be replaced by data2.This is the part of the program i have written so far. But unfortunately its not working. The program takes string by string to check the occurences. Can anyone help me how to correct it?I will really appreciate it.

void replace(string& data, const string& data1,string& data2) {
	int occurence = 0;
	while (occurence < data.length())
	{
	    occurence = data.find(data1);
	    if (occurence >= 0) {
		    data.replace(occurence,data1.length(),data2);
	    }
	}
}

When find() failes it returns std::string::npos, which is an unsigned integer. So testing with an integer is useless.

size_t pos;
while( (pos = data.find(data1)) != string::npos)
{
     data.replace(pos,data1.length(),data2);
}

The danger with the above is when data1 contains data2. In that case the above would become an infinite loop.

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.