如何将csv文件中的值加载到2d向量<double>?

时间:2017-03-20 22:18:29

标签: c++ csv vector 2d

我有一个包含5列和100行的csv文件。 我的目标是将文件加载到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 Vector中?

来自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

1 个答案:

答案 0 :(得分:-1)

这里至少有两个问题:

  1. 您试图将整行(在文件的情况下由多个数字组成)推入向量。所以你还需要用逗号分隔这行。

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

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

    我想到的第一个将字符串转换为双精度的方法是atof(它实际上将c_string转换为float,但希望你可以处理字符串到c_string和float到a的转换双

    由于某些安全问题,有些人真的很讨厌,并且它们并非完全错误,但它可能只是您的计划所需要的。

  3. 对于这两个问题,您不应该在搜索堆栈溢出时遇到任何问题,以找到如何执行这些操作的示例。

    此外,我注意到您的示例文件看起来像每列指示不同类型的数据。最有可能的是,您实际上并不希望将它们存储在矢量中,而是存储在某个二维对象中(例如矢量&gt;)。