我正在while循环中读取CSV文件的行。我想在while循环之外使用CSV文件的最后一行。但是我不能把它打印在屏幕上。我没有任何类型的错误。基本上,我想得到CSV文件的最后一行,但我不能使用它。
#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
------
假设您的CSV数据如下所示:
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
我假设你想得到输出,最后一行是---1,2,3---
,在最后一行之前没有重复。
所以解决方案是
#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;
}
其思想是在调用getline()
之后检查下一个字符。
输出:
362.8824443359375,548.4825712890625,-22.28239796447754,8
...
...
...
---1,2,3---