erdarshp
erdarshp

Reputation: 443

how can i read last line of file

I tried this after reading the file programe get closed. it is not showing the last line of file, which should be in the new1 string pointer after complete reading.

#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main () {
std::string line;
int i;
std::string *new1;
new1 = new string;
ifstream myfile ("path.txt");
   while (myfile)
   {
         getline (myfile,line);
         cout << line<<endl;
         new1=line;

   }              
   cout<<new1<<endl;
   myfile.close();
      cin.get();
      return 0;
}

thanks in advance .

Upvotes: 1

Views: 7606

Answers (2)

Dhirendra
Dhirendra

Reputation: 790

This is because the last value comes in line before terminating the loop is eof.

use this:

while (getline (myfile,line))
{
    cout << line<<endl;
    new1=line;

}

Upvotes: 0

R Sahu
R Sahu

Reputation: 206737

The main change to your code:

Replace

while (myfile)
{
     getline (myfile,line);
     cout << line<<endl;
     new1=line;

}

by

while (getline (myfile,line))
{
   cout << line<<endl;
   new1=line;
}              

The reason the first one does not work is that after you have finished reading the last line, while (myfile) continues to evaluate to while(true). At that time, getline(myfile, line) doesn't succeed. You are not catching that return value and dealing with it properly.

Other improvment:

Replace

std::string *new1;
new1 = new string;

by

std::string new1;

Not sure why you thought you needed new1 to be a pointer. If you continue to keep new1 as a pointer, you'll have to change the while loop to:

while (getline (myfile,line))
{
   cout << line<<endl;
   *new1=line;  // *new1, not new1.
}

Of course you'll have to add a line to delete new1 too.

Upvotes: 1

Related Questions