我有一個csv文件,5列和100行。 我的目標是將文件加載到一個vectorData如何將csv文件中的值加載到2d矢量<double>?
#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
另外,'vector data;'不是一個2D矢量。 'vector > data;'可能儘可能接近您的需要,但由於空間局部性較差可能會變慢。如果你總是有5列'vector '應該會更快。 –
user4581301
'while(!myfile.eof())'是一個常見的錯誤。更多關於這裏:http://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong – user4581301
,並沒有指向'計數++;'。 'vector'知道它有多大。 'cout <<「的日誌計數是:」<< data.size()<< endl;'會做你所需要的。 – user4581301