如何将值从 csv 文件加载到 2d 矢量<double>?



我有一个 csv 文件,有 5 列 100 行。 我的目标是将文件加载到vectorData中

#include <iostream>
#include <fstream> 
#include <string>
#include <vector>
using namespace std; 
int main()
{
int count = 0;
vector<double> data;
string line;
cout << "Testing loading of file." << endl;
ifstream myfile ("iris.csv");
if ( myfile.is_open() )
{
while ( ! myfile.eof() )
{
getline (myfile, line);
data.push_back(line);
// logs.at(count) = line;
count++;
}
myfile.close();
}else{
cout << "Unable to open file." << endl;
}
cout << "the log count is: " << count << endl;
return 0;
}

我尝试编写上面的代码以在向量中输入 1 个值,但是当我尝试编译时出现错误

lab6.cpp: In function ‘int main()’:
lab6.cpp:22:35: error: no matching function for call to                        ‘std::vector<double>::push_back(std::__cxx11::string&)’
data.push_back(line);
^
In file included from /usr/include/c++/6.3.1/vector:64:0,
from lab6.cpp:4:
/usr/include/c++/6.3.1/bits/stl_vector.h:914:7: note: candidate: void             std::vector<_Tp, _Alloc>::push_back(const value_type&) [with _Tp = double; _Alloc = std::allocator<double>; std::vector<_Tp, _Alloc>::value_type = double]
push_back(const value_type& __x)
^~~~~~~~~
/usr/include/c++/6.3.1/bits/stl_vector.h:914:7: note:   no known     conversion for argument 1 from ‘std::__cxx11::string {aka std::__cxx11::basic_string<char>}’ to ‘const value_type& {aka const double&}’
/usr/include/c++/6.3.1/bits/stl_vector.h:932:7: note: candidate: void std::vector<_Tp, _Alloc>::push_back(std::vector<_Tp, _Alloc>::value_type&&) [with _Tp = double; _Alloc = std::allocator<double>; std::vector<_Tp, _Alloc>::value_type = double]
push_back(value_type&& __x)
^~~~~~~~~
/usr/include/c++/6.3.1/bits/stl_vector.h:932:7: note:   no known conversion for argument 1 from ‘std::__cxx11::string {aka std::__cxx11::basic_string<char>}’ to ‘std::vector<double>::value_type&& {aka double&&}’

有人可以指出我如何修改代码或从头开始以将值加载到 2d 矢量的正确方向吗?

CSV 文件中的示例数据。

-0.57815,0.83762,-1.0079,-1.0369,-1
-0.88983,-0.20679,-1.0079,-1.0369,-1
-1.2015,0.21097,-1.0769,-1.0369,-1
-1.3573,0.0020888,-0.93891,-1.0369,-1
-0.73399,1.0465,-1.0079,-1.0369,-1
-0.11064,1.6731,-0.80094,-0.683,-1
-1.3573,0.62874,-1.0079,-0.85994,-1

这里至少有 2 个问题:

  1. 您正在尝试将整行(在您的文件由多个数字组成的情况下)推入向量。因此,您还需要用逗号分隔行。

    我会使用 strtok 来拆分字符串。

  2. vector.push_back() 需要 double 类型的参数,但您正在向其传递一个字符串。必须先将字符串转换为双精度值。

    我想到的第一种方法是 atof(它实际上将c_string转换为浮点数,但希望您可以处理字符串到c_string和浮点数到双精度的转换。

    由于一些安全问题,有些人真的很讨厌atof,他们并不是完全错误的,但它可能是你的程序所需要的。

对于这两个问题,搜索堆栈溢出以查找如何解决这些问题的示例应该不会有任何麻烦。

另外,我注意到您的示例文件看起来像每列都表示不同类型的数据。最有可能的是,您实际上不想将它们存储在向量中,而是存储在一些二维对象(例如 vector>)中。

相关内容

最新更新