0

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);
	    }
	}
}

Edited by WolfPack: added [CODE][/CODE] tags

2
Contributors
1
Reply
3
Views
7 Years
Discussion Span
Last Post by Ancient Dragon
0

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.

Edited by Ancient Dragon: n/a

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.