C++ 读取CSV文件、分割字符串
一、字符串分割
static std::vector<std::string> getWords(const std::string &s, const std::string &delim)
{
std::vector<std::string> res;
//std::string delim = ",";
std::string token = "";
for (int i = 0; i < s.size(); i++) {
bool flag = true;
for (int j = 0; j < delim.size(); j++) {
if (s[i + j] != delim[j]) flag = false;
}
if (flag) {
if (token.size() > 0) {
res.push_back(token);
token = "";
i += delim.size() - 1;
}
} else {
token += s[i];
}
}
res.push_back(token);
return res;
}
二、读取CSV格式文件
static void Load_Full_IMU_Data(const std::string &csv, std::vector<Eigen::Vector3d> &gyro, \
std::vector<Eigen::Vector3d> &acce, std::vector<Eigen::Vector3d> &magn)
{
FILE *fp = fopen(csv.c_str(), "r");
if(nullptr == fp)
return;
char buf[2048] = "";
while(fgets(buf, sizeof(buf), fp)){
std::vector<std::string> all_str = getWords(std::string(buf), ",");
if(all_str.size()>=9){
Eigen::Vector3d acc;
Eigen::Vector3d gyr;
Eigen::Vector3d mag;
double t = strtod(all_str[0].c_str(), nullptr);
double gyrox = strtod(all_str[1].c_str(), nullptr);
double gyroy = strtod(all_str[2].c_str(), nullptr);
double gyroz = strtod(all_str[3].c_str(), nullptr);
gyr[0] = gyrox;
gyr[1] = gyroy;
gyr[2] = gyroz;
gyro.push_back(gyr);
double accex = strtod(all_str[4].c_str(), nullptr);
double accey = strtod(all_str[5].c_str(), nullptr);
double accez = strtod(all_str[6].c_str(), nullptr);
acc[0] = accex;
acc[1] = accey;
acc[2] = accez;
acce.push_back(acc);
double magnx = strtod(all_str[7].c_str(), nullptr);
double magny = strtod(all_str[8].c_str(), nullptr);
double magnz = strtod(all_str[9].c_str(), nullptr);
mag[0] = magnx;
mag[1] = magny;
mag[2] = magnz;
magn.push_back(mag);
}
memset(buf, 0x00, sizeof(buf));
}
fclose(fp);
return;
}