Infinite loop in unexpected place
Infinite loop in unexpected place
I try to create a function, that delete chosen string is a text file. But in lines 56-64 I get an infinite loop - whereas file.txt contains only 8 strings, not eternity)
int delNStr(int N, string way)
{
ifstream log(way, ios_base::in);
ofstream temp("C:TempLoadLogger.txt", ios_base::trunc | ios_base::app);
int num = 0;
while (!log.eof())
{
if (num != N)
{
string currier;
getline(log, currier);
temp << currier;
};
}
log.close(); temp.close();
ofstream log2(way, ios_base::trunc | ios_base::app);
ifstream temp2("C:TempLoadLogger.txt", ios_base::in);
while (!temp2.eof())
{
string currier;
getline(temp2, currier);
log2 << currier;
}
log2.close(); temp2.close();
delete ("C:TempLoadLogger.txt");
return 0;
}
I call this function in main:
delNStr(0, "C:UsersUserDesktopprogectsfile.txt");
Is all OK?
P.S. I know, that i sould use void. But in that case is does not matter.
while (!log.eof())
delete ("C:TempLoadLogger.txt");
@NathanOliver My guess? They want to delete that file...
– Borgleader
Jun 29 at 17:33
@Borgleader That's a good guess. I hadn't even considered that. I thought they were trying to clean up the string literal.
– NathanOliver
Jun 29 at 17:34
You never change
num
. So, when num == N
(which is the case when you call as shown above), then you will never read from the file and eof()
will never be true. Please learn how to use a debugger and you will be able to find problems like these yourself.– Adrian W
Jun 29 at 17:36
num
num == N
eof()
Read the link. It explains how to change the condition to work correctly.
– NathanOliver
Jun 29 at 17:51
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
First, do not use
while (!log.eof())
. Second, why are you doingdelete ("C:TempLoadLogger.txt");
?– NathanOliver
Jun 29 at 17:30