C/C++教程

基于C++的txt文档log数据提取

本文主要是介绍基于C++的txt文档log数据提取,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

 

#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;
}

这篇关于基于C++的txt文档log数据提取的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!