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;
}
3
  • @walnut even after removing the &&!fin.eof() the loop is still runing for infinite times. Commented Dec 21, 2019 at 14:17
  • I have tried '!line.empty()' in the condition too but it's still not working and runing for infinite times. Commented Dec 21, 2019 at 14:19
  • What if the file doesn't exist. Commented Dec 21, 2019 at 14:59

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.