wont read last line from file?

So i have an almost complete program but it will not read the last line? what do i need to change for this program to work using fin.eof() or the infinite while(1) loop?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
#include <iostream>
using std::cin;
using std::cout;
using std::endl;

#include <fstream>
using std::ifstream;
using std::ofstream;

int main()
{
 // declare char array to store input
  char input[50];
  char file[50];
  char buf[512];

  cout << endl;
  // Prompt user to enter the file name they want to pull text from
  cout << "Please enter the full path name of the file you would like to access: \n";
  cin.getline(input, 50);
  
  // open up the file 
  ifstream fin;
  fin.open(input);
  // test if the input file is valid if not return
  if (!fin.good())
  {
    cout << "The file was not found \n";
    return 1;
  }
  cout << endl;
  // ask what file they would like to copy first file into
  cout << "Now chose name of file you would like to copy the contents of " << endl;
  cout << input << " file into: ";
  cin.getline(file, 50);
  ofstream fout;
  fout.open(file);
  cout << endl;

  // 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; 
  }
    fin.close();  
	
    
     
	   
      // if no valid export file is input return invalid entry
      if (fout.good())
      {
	    cout << endl;
        cout << "The file was not found \n";
        return 1;
      }
	  else
	  {
      	  fout.close();     
      }
	  return 0;
}
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;
    }

Last edited on
Topic archived. No new replies allowed.