【发布时间】:2020-02-20 14:43:53
【问题描述】:
例如添加以下 CSV 数据:
我正在尝试将 CSV 文件添加到二维数组字符串向量中并获取每列的总和。以下程序无法正常运行,
vector<string> read_csv(string filename){
vector<string> result;
fstream fin;
fin.open(filename, ios::in);
if(!fin.is_open())
throw std::runtime_error("Could not open file");
std::string line, colname;
int val;
// Read the column names
if(fin.good())
{
std::getline(fin, line);
std::stringstream ss(line);
while(std::getline(ss, colname, ',')){
result.push_back(colname);
cout << colname << endl;
}
}
while(std::getline(fin, line))
{
std::stringstream ss(line);
int colIdx = 0;
while(ss >> val){
if(ss.peek() == ',') ss.ignore();
colIdx++;
}
}
fin.close();
return result;
}
当我试图通过向量时,我没有得到正确的结果。它只显示列名。
for (int i = 0; i < vectorCsv.size(); ++i)
{
cout << vectorCsv[i] << endl;
}
我找不到错误是在 read_csv() 函数中还是在 forloop 中。 感谢您查看此问题。
【问题讨论】:
-
我强烈推荐使用库,在 C++ 中解析字符串(和文件)非常繁琐
-
@const_ref 库很棒,但我想这个人正处于学习阶段(从代码和问题来看),所以在我看来,这是一个有益的练习
-
你在返回的向量中真正添加了什么?
-
我找不到错误是在 read_csv() 函数中还是在 forloop 中 -- 你使用的是调试器吗?找出错误在哪里是您应该能够做的——修复错误是另一回事。
-
还要记住你尝试读取整数值,但是你的第二次读取循环只会读取日期和时间的第一个数字,然后
ss >> val会失败。