从CSV文件C 读取和分类
Reading and sorting from CSV file C++
你好,所以我需要一个从.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];
}
在排序时将字符串转换为int
或double
。您还可以使用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
转换。如评论中所建议的,您可以使用结构。
相关文章:
- 理解boost::asio-async_read在无需读取内容时的行为
- 使用新行和不使用新行读取文件
- 读取文件并输入到矢量中
- 用c++从输入文件中读取另一行
- 读取文件的最后一行并输入到链接列表时出错
- 在进程中对同一管道进行读取和写入时C++管道出现问题
- 无法找到/读取配置文件.conf-FileIOException
- 如何使用Luacneneneba API正确读取字符串和表参数
- C++将文本文件中的数据读取到结构数组中
- 正在将csv文件读取为双精度矢量
- 为什么 sscanf 无法从一个字符串中读取uint64_t和字符?
- 为什么在读取文件大小时文件IO速度会发生变化
- 正在读取二进制文件(is_open)
- 如何在c++中从文本文件中逐行读取整数
- SSH通过/sbin/SSH无法读取RSA密钥文件(从控制台运行)
- 独立读取-修改-写入顺序
- 从文本文件中读取时钟时间和事件时间并进行处理
- 如何从文本文件中读取值和数组
- 如何读取文件并将该文件分类为不同类型的数据,这些数据都存储在结构中的特定数组中
- 从CSV文件C 读取和分类