infinite loop with string.insert

The following code works if i leave out the lineIn.insert(i,"\n"); line.
when i put that line in, the program goes into an infinite loop.
I am trying to read a line of text from a text file and insert a newline where
str1 is found. It acts like a internal pointer is being reset to the first
part of the string when i use the insert function.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
if (inFile.good()) //if the file opened
  {
	do {
		getline(inFile,lineIn);
		for(i = lineIn.find(str1, 0); i != string::npos; i = lineIn.find(str1, i))
		{
			cout << "found str1 at " << i << endl;
			lineIn.insert(i,"\n");
			i++;
		}
		
	} while (! inFile.eof());
	
  } //end if 
Do a desk test.
You've got an infinite loop because you always find the string.
something else i discovered, the lineIn string does get str1 inserted into it, but it is always the first string read from the file and it continues to put the str1 into the first string until eof.

what is a desk test?
Go to a desk with pen and paper.
Simulate your program (act as the computer)


By the way, you should read as
1
2
3
while( getline(inFile, lineIn) ){
   //...
}
thank you for your reply.

the infinite loop only occurs when i put the lineIn.insert(i,"\n"); line in.
You always insert the new line character before str1. Then you increase i that again points to str1. So the same value of str1 will be found next time. In fact your code does the following


\n\n\n...\nstr1
Topic archived. No new replies allowed.