我从另一个类似问题的答案中获得了此代码,但是我不知道为什么这对我不起作用。 test.csv与已编译的.exe文件位于同一文件夹中,但找不到该文件。我尝试了完整的系统路径(“ C:\ Users \ hhv \ eclipse-workspace \ oncemore \ Debug \ test.csv”),但仍然无法打开csv。
所以我对正在发生的事情不知所措,因为我看过的所有其他示例都应该正常工作。例如:https://github.com/tpatil2/C-Programs/blob/master/RWcsv/rwcsv.cpp
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <vector>
#include "load_symbol.h"
using namespace std;
bool load_symbols(){
string line; /* string to hold each line */
vector<vector<int>> array; /* vector of vector<int> for 2d array */
ifstream f ("test.csv"); /* open file */
if (!f.is_open()) { /* validate file open for reading */
perror ("error while opening symbol file ");
return false;
}
while (getline (f, line)) { /* read each line */
string val; /* string to hold value */
vector<int> row; /* vector for row of values */
stringstream s (line); /* stringstream to parse csv */
while (getline (s, val, ',')) /* for each value */
row.push_back (stoi(val)); /* convert to int, add to row */
array.push_back (row); /* add row to array */
}
f.close();
cout << "complete array\n\n";
for (auto& row : array) { /* iterate over rows */
for (auto& val : row) /* iterate over vals */
cout << val << " "; /* output value */
cout << "\n"; /* tidy up with '\n' */
}
return true;
}
该路径是相对于当前工作目录(执行程序的位置),而不是相对于源文件。同样,当您在文件路径中使用反斜杠时,也必须像“ C:\\ Users \\ hhv \\ eclipse-workspace \\ oncemore \\ Debug \\ test.csv”那样对它们进行转义]