使用回推 c++ 读取特定的数据列
Read specific columns of data using pushback c++
我有一个输入文件,其中包含具有不同数据类型的不同数据列。
我需要读取前两列,它们都是浮点数,其中第 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::getline
、std::string
和std::istringstream
的用法可以通过搜索StackOverflow或互联网轻松找到。
相关文章:
- C++将文本文件中的数据读取到结构数组中
- 为 Sql 服务器实现 odbc 包装器.将数据库数据读取为字符或要求驱动程序将数据转换为 C 类型
- 如何将来自文本文件的数据读取到结构的int阵列中
- 如何将不同长度的数据读取到 2D 数组中
- 从TXT文件到C 的结构向量中的数据读取
- 将sqlite原始数据读取到qbyTearray
- 如何将来自输入TXT文件的数据读取到2 C 数组中
- 使用MQQueue将数据读取到缓冲区中时麻烦
- 在 VC++ 中将类数据读取和写入二进制文件
- 将数据从数据读取器终端获取到GUI(QtCreator)
- C 将数据读取到一个结构,但它跳过了我的一个获取线,使该元素空白
- C++将二进制数据读取到结构
- c++我需要将文件中的数据读取到多维数组中,然后用一种数据类型对数组进行排序.怎样
- 对齐数据:速度取决于恒定数据读取的相对采样大小和采样频率
- 如何将文件中的数据读取到数组中
- 如何使用Visual C++应用程序的完整应用程序数据读取Minidump的应用程序数据
- 如何将csv文件数据读取到数组中
- 用C++将格式化的数值数据读取到数组中
- 正在从文件中将数据读取到结构数组中
- 将分离的数据读取到数组结构c++中