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

时间:2018-08-23 16:08:52

标签: c++

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

我需要读取前两列,它们都是浮点数,其中第一列是纬度,第二列是经度。我想读取数据并将其存储在可以携带经度和纬度的向量中。

我已经使用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;
}

有人可以解释如何进行上述尝试,从我的数据文件中读取我的经纬度并将其存储到向量中吗?

目前,我没有从上面得到任何输出。

(您可能已经得出结论,我不是一个熟练的程序员)

1 个答案:

答案 0 :(得分:1)

一种用于执行此操作的 more C ++ ish 方法是:
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;
}

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