There's something missing from the code above:
40 41 42 43 44 45 46
|
// loop to read individual lines from file and print each line on output
fin.getline(buf, 512);
while(!fin.eof())
{
cout << buf << endl;
fout << buf << endl;
}
|
There is no input statement inside the while loop. Therefore the state of
!fin.eof()
does not change and this gives an infinite loop.
A first attempt at a solution might look like this:
1 2 3 4 5 6 7
|
fin.getline(buf, 512);
while(!fin.eof())
{
cout << buf << endl;
fout << buf << endl;
fin.getline(buf, 512);
}
|
But there's still a problem. Testing for
.eof()
is almost always an error, and should be avoided.
In this case, when reading the last line, the getline requests 512 characters. If the line contains less than 512 characters (which is quite likely), the eof flag is set and the loop terminates without writing that line to the output file.
One answer is to use
fin.fail()
instead of
fin.eof()
But a better solution is to put the read statement in the while condition, like this:
1 2 3 4 5
|
while(fin.getline(buf, 512))
{
cout << buf << endl;
fout << buf << endl;
}
|