0

I am reading rows of the CSV file in a while loop. I want to use last row of the CSV file outside of the while loop. But i cant print it on the screen. I dont get any type of error. Basically i want to get last row of the CSV file but i could not using that.

#include <iostream>
#include <fstream>
#include <string> 
using namespace std;


void read(){
  ifstream route;
  string lastLine;
  route.open("/home/route2.csv");

  while(!route.eof())
  {
    getline(route,lastLine);
    cout<<lastLine<<endl; 
  }

  cout<<"---"<<lastLine<<"---"<<endl; //This line does not print the lastLine
  route.close();

}

int main (int argc, char** argv)
{ 

read();

return 0;
}
My output is like that

Data
Data
Data
Data
318.4821875,548.7824897460938,-22.28279766845703,8.1
362.8824443359375,548.4825712890625,-22.28239796447754,8.82
361.1825078125,548.1822817382812,-22.28289794921875,8.82


------

1 Answers1

0

Suppose your CSV data is something like this:

362.8824443359375,548.4825712890625,-22.28239796447754,8.82
361.1825078125,548.1822817382812,-22.28289794921875,8.82
318.4821875,548.7824897460938,-22.28279766845703,8.1
362.8824443359375,548.4825712890625,-22.28239796447754,8.82
361.1825078125,548.1822817382812,-22.28289794921875,8.82
1,2,3

I assume you want to get output the last line is ---1,2,3--- without duplication before the last line.

So the solution is

#include <iostream>
#include <fstream>
#include <string>

using namespace std;

void read() {
  ifstream route;
  string lastLine;
  route.open("/home/route2.csv");

  while (!route.eof()) {
    getline(route, lastLine);

    // Check next character
    if (route.peek() != EOF)
      cout << lastLine << endl;
  }

  cout << "---" << lastLine << "---" << endl;
  route.close();

}

int main(int argc, char ** argv) {

  read();

  return 0;
}

The idea is to check next character after getline() invoked.

Output:

362.8824443359375,548.4825712890625,-22.28239796447754,8
...
...
...
---1,2,3---
afifabroory
  • 11
  • 1
  • 4