Why does this give me an infinite loop?

This code is to read a file line by line. But it never stops running unless I leave the exit methods. What's wrong with it?


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
void file::read(std::string fn) {

    using namespace std;

    string line;
    ifstream myfile;

    myfile.open(fn.c_str());

    if(!myfile) {
        cout << "File failed to open" << flush;
        cin.ignore();
        exit(1);
    }

    if (myfile.is_open()) {
        while (getline (myfile,line) && !line.empty()){
            cout << line << endl;
        }
    }
    myfile.close();
    //exit(1);
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
void file::read(std::string fn) {

    using namespace std;

    string line;
    ifstream myfile;

    myfile.open(fn.c_str());

    if(!myfile) {
        cout << "File failed to open" << flush;
        cin.ignore();
        exit(1);
    }

    if (myfile.is_open()) {
        while (getline (myfile,line) && !line.empty()){
            cout << line << endl;
        }
    }
    myfile.close();
    //exit(1);
}

First of all, let me fix that code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
void file::read(std::string fn)
{
    using namespace std;

    ifstream myfile(fn.c_str());
    if (!myfile)
    {
        cout << "File failed to open" << flush;
        cin.ignore();
        exit(1);
    }

    string line;
    while (getline(myfile,line) && !line.empty())
    {
        cout << line << endl;
    }
    //exit(1);
}

Let the constructor and destructor help you to write simpler (and more correct) code.

You get an infinite loop unless you leave in the exit() because the calling function must call file::read() in an infinite loop.

Step out of the function in a debugger to see which function calls it and debug that function.
Last edited on
Thanks for that, I've fixed the infinite loop. So it's not necessary to call the close method?
Last edited on
Topic archived. No new replies allowed.