【发布时间】:2018-02-17 17:27:25
【问题描述】:
大家好,我需要一个从 .csv 文件读取到动态二维数组或向量的项目的帮助。 CSV 文件包含游泳比赛的详细信息,我应该在其中读取不同距离和时间的名称时间和距离。然后我需要使用时间和距离对它们进行排序,用户应该能够根据距离搜索比赛,并且应该向他/她显示一定距离内的最快时间。 这是我的代码,它没有按时间对值进行排序,因为尽管我尝试将其转换为 int,但它仍然是字符串格式。
#include <iostream>
#include <fstream>
#include <iomanip>
#include <algorithm>
#include <vector>
#include <sstream>
using namespace std;
bool sortByTime(const vector<int>& v1,const vector<int>& v2 );
int main(){
vector< vector<string> > heatLevels;
ifstream in("code.csv");
if(!in)
cout<< "File not found"<< endl;
string line,sector;
vector<string> v;
while(getline(in,line)){
v.clear();
stringstream ss(line);
while (getline(ss,sector,',')) // break line into comma delimited sectors
{
v.push_back(sector); // add each sector to the 1D array
}
heatLevels.push_back(v); // add the 1D array to the 2D array
}
for(int i = 0; i< heatLevels.size(); i++)
{
for(int j = 0; j<heatLevels[i].size(); j++)
{
cout<<heatLevels[i][j]<< setw(12);
}
cout<< "\n";
}
for(int i = 1; i< heatLevels.size(); i++)
{
int j=5;
stringstream converter(heatLevels[i][j]);
float x =0.0;
converter >> x;
}
//Sort table by time
sort(heatLevels.begin()+1, heatLevels.end(),sortByTime);
}
bool sortByTime(const vector<int>& a,const vector<int>& b )
{
return a[5] < b[5];
}
【问题讨论】:
-
那是因为你有一个字符串向量和一个字符串向量向量。也许你在找我们
std::stoi? -
您的问题是在阅读
CSV文件还是只是对结果进行排序? -
解决这个问题的方法是为记录声明一个 POD(纯数据)结构,然后通过 CSV 将每一行转换为一个结构并将它们放入一个向量中,然后调用 std::对向量进行排序。
-
我不明白。搜索“StackOverflow C++ 读取文件 CSV”会产生大量示例。我不明白为什么人们不先搜索或使用调试器。
-
@ThomasMatthews 我已经在 Stack Overflow 上搜索过,没有一个与我的相似
标签: c++