#include <vector>
#include <string>
#include <iostream>
#include <cstring>
#include <stdio.h>
#include <math.h>
#include <fstream>
#include <sstream>
std::vector<std::string> split(const std::string& str, const std::string& delim)
{
std::vector<std::string> res;
if("" == str) return res;
//先将要切割的字符串从string类型转换为char*类型
char * strs = new char[str.length() + 1] ;
strcpy(strs, str.c_str());
char * d = new char[delim.length() + 1];
strcpy(d, delim.c_str());
char *p = strtok(strs, d);
while(p) {
std::string s = p;
res.push_back(s);
p = strtok(NULL, d);
}
return res;
}
int readTxtData(std::string fileName, std::string dataName, std::vector<double>& radius_x)
{
std::ifstream myfile(fileName);
if (!myfile.is_open())
{
std::cout << "Unable to open file:" << fileName << std::endl;
return -1;
}
std::vector<std::string> vec;
std::string temp;
bool isReadDataName = false;
int dataNum = -1;
while (getline(myfile, temp))
{
if(isReadDataName)
vec.push_back(temp);
else
{
std::vector<std::string> result = split(temp, "\t");
for(int i = 0; i < result.size(); i++)
{
if(result[i] == dataName)
{
dataNum = i;
std::cout << "dataNum:" << dataNum << std::endl;
isReadDataName = true;
break;
}
}
if(dataNum < 0)
{
myfile.close();
return -2;
}
}
}
for (auto it_x = vec.begin(); it_x != vec.end(); it_x++)
{
// std::cout << *it_x << std::endl;
std::istringstream is(*it_x);
std::string s_x;
int pam = 0;
while (is >> s_x)
{
if (pam == dataNum)
{
double r_x = atof(s_x.c_str());
radius_x.push_back(r_x);
}
pam++;
}
}
return 0;
}
int main()
{
std::vector<double>& radius_x;
readTxtData("speedLog.txt", "x", radius_x);
std::cout << radius_x << std::endl;
}