1

The while loop is running for infinite times although I have a check for EOF in the while condition. But it's still running for infinite times. Below is my code:

int code;
cin >> code;
std::ifstream fin;

fin.open("Computers.txt");

std::ofstream temp; // contents of path must be copied to a temp file then renamed back to the path file
temp.open("Computers.txt", ios_base::app);


string line;
string eraseLine = to_string(code);
while (  getline(fin, line) && !fin.eof() ) {
    if (line == eraseLine)
    {
        /*int i = 0;
        while (i < 10)
        {*/
            temp << "";
            //i++;
        //}
    }
    if (line != eraseLine) // write all lines to temp other than the line marked for erasing
        temp << line << std::endl;
}
Alexander van Oostenrijk
  • 3,691
  • 1
  • 16
  • 32
Aqleema Sajid
  • 79
  • 1
  • 4

1 Answers1

9

You claim in the comments that temp should refer to a temporary file, but that is not the case. You open the same file for appending from which you are already reading with fin.

Since you keep appending while iterating the loop, there will always be new stuff in the file to be read, causing the infinite loop (until you run out of disk space).

Use a different file name for your temp stream and rename it later (as the comment says).


Also remove && !fin.eof(). It serves no purpose. while ( getline(fin, line) ) is a proper way to handle line-by-line reading until the end-of-file, see e.g. this question and this one.

walnut
  • 20,566
  • 4
  • 18
  • 54