从CSV文件C 读取和分类

Reading and sorting from CSV file C++

本文关键字:分类 读取 CSV 文件      更新时间:2023-10-16

你好,所以我需要一个从.csv文件读取到动态2D数组或向量的项目的帮助。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];
}

在排序时将字符串转换为intdouble。您还可以使用lambda功能使其更容易:

int main() 
{
    vector<vector<string>> heatLevels;
    ifstream in("code.csv");
    if(!in)
        cout << "File not found" << endl;
    string line, sector;
    while(getline(in, line)) 
    {
        vector<string> v;
        stringstream ss(line);
        while(getline(ss, sector, ',')) 
            v.push_back(sector);  
        heatLevels.push_back(v); 
    }
    for(auto &row : heatLevels)
    {
        for(auto &e : row)
            cout << e << ",";
        cout << "n";
    }
    auto sortproc = [](const vector<string> &a, const vector<string> & b)
    {
        double ia, ib;
        try
        {
            ia = std::stod(a[5]);
            ib = std::stod(b[5]);
        }
        catch(...)
        {
            cout << "invalid or out of rangen";
            return false;
        }
        return ia < ib;
    };
    std::sort(heatLevels.begin(), heatLevels.end(), sortproc);
    cout << "sorted:n";
    for(auto &row : heatLevels)
    {
        for(auto &e : row)
            cout << e << ",";
        cout << "n";
    }
    return 0;
}

上面的方法足够快,但这不是最有效的方法,因为您进行了很多string-> int转换。如评论中所建议的,您可以使用结构。