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
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.
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