-4

I sort of cringe at the sight of extensive file operation in code. But good old freopen() has failed me in this particular code segment-

int main()
{
    ifstream fin;
    int next=0;
    fin.open("In.txt");
    if(fin.is_open())
    {
        while(!fin.eof())
        {
            cout<<next;
            next++;
        }
    }
    else cout<<"Unable to open file"<<endl;
    return 0;
}

The headers I included are iostream, fstream and cstdio. This goes into an infinite loop.

My question is, the file I gave as input definitely has an end. But why doesn't the program terminate? Thanks in advance.

indiv
  • 17,306
  • 6
  • 61
  • 82
  • 7
    You're not reading from the file, which means that you're not getting to the end of the file. – Roger Lipscombe Oct 22 '14 at 18:58
  • 4
    Of course you're never going to reach EOF without reading anything. You shouldn't be using `eof()` as a terminating condition anyway. Check input operations for success before assuming they succeeded. – chris Oct 22 '14 at 18:58
  • 3
    `while(!fin.eof())` Related: [Why is iostream::eof inside a loop condition considered wrong?](http://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong) – πάντα ῥεῖ Oct 22 '14 at 19:02

2 Answers2

2

You should almost never use eof() as an exit condition for a file reading loop. Try

std::string line;
if(fin.is_open())
{
    while(getline(fin, line))
    {
        cout<<line;
    }
}

If you explain what next was actually supposed to do I can try to tell you how to do it, though I personally usually read files with getline or operator>> which doesn't require any control integers.

IllusiveBrian
  • 3,105
  • 2
  • 14
  • 17
0

You're opening a file and actually not reading from it. Every time you check if you have reached the end of the file the stream is on the same position.

So change it to something like this :

string word;
while(!file.eof()) {
  file >> word;
  cout << next;
  next++;
}
Ammaro
  • 370
  • 2
  • 14
  • 1
    [Why is iostream::eof inside a loop condition considered wrong?](http://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong) – πάντα ῥεῖ Oct 22 '14 at 19:04