使用回推 c++ 读取特定的数据列

Read specific columns of data using pushback c++

本文关键字:数据 读取 c++      更新时间:2023-10-16

我有一个输入文件,其中包含具有不同数据类型的不同数据列。

我需要读取前两列,它们都是浮点数,其中第 1 列是纬度,第 2 列是经度。我想读取数据并将其存储在可以同时承载纬度和经度的向量中。

我使用struct为经度多头头寸创建变量,我正在尝试将它们作为一个point一起读取。谁能解释一种更C++的方法,或者如何让我的方法起作用?或者,我可以使用getline直接推回两列数据,但对这种方法的理解也回避了我。

计划是能够访问这些经度points以便我可以对特定点进行距离计算。

我的输入文件等效于

#Latitude   Longitude   Depth [m]   Bathy depth [m] CaCO3 [%]
-78 -177    0   693 1
-78 -173    0   573 2
-78 -168    0   592 -999
-78 -162    0   668 2
-77 -178    0   640 2
-77 -174    0   573 1

我的尝试如下:

#include <iostream>
#include <sstream>
#include <fstream>
#include <vector>
#include <string>
struct Point
{
double latitude, longitude;
};
using namespace std;
int main ()
{
ifstream inputFile("Data.txt");
std::vector<Point> database;
Point p;
float latit, longit;
if (inputFile.is_open())
{
while(inputFile >> latit >> longit)
{
//        database.push_back(Point{latit, longit});
database.push_back(p);
cout<<p.longitude << " " << p.latitude << endl;
}
inputFile.close();
}
else {
cout <<"Unable to open file";
}
return 0;
}

谁能解释一下我上面尝试从数据文件中读取我的经纬度长点并将其存储到向量中?

目前,我没有得到上述输出。

(我不是一个流利的程序员,你可能已经得出结论了(

一个更C++的方法是:
1. 结构的重载operator>>
2. 在结构中创建距离方法。
3. 结构中的重载运算符<和>

超载operator>>

struct Point
{
double latitude;
double longitude;
friend std::istream& operator>>(std::istream& input, Point& p);
};
std::istream& operator>>(std::istream& input, Point& p)
{
input >> p.latitude;
input >> p.longitude;
return input;
}

您的输入可能是:

std::vector<Point> database;
Point p;
while (data_file >> p)
{
database.push_back(p);
}

编辑 1:operator>>用于阅读行

std::istream&
operator>>(std::istream& input, Point p)
{
std::string row_text;
std::getline(input, row_text);
std::istringstream row_stream(row_text);
row_stream >> p.latitude;
row_stream >> p.longitude;
return input;
}

std::getlinestd::stringstd::istringstream的用法可以通过搜索StackOverflow或互联网轻松找到。