C++ txt文件数据解析和生成txt文件代码
一、txt文件数据解析代码
#include <string>
#include <fstream>
#include <iostream>
#include <sstream>
template <class Type>
Type stringToNum(const std::string& str)
{
std::istringstream iss(str);
Type num;
iss >> num;
return num;
}
typedef std::string::size_type string_size;
static std::vector<std::string> splitString(const std::string &s, const std::string &seperator)
{
std::vector<std::string> result;
string_size i = 0;
while(i != s.size())
{
//找到字符串中首个不等于分隔符的字母;
int flag = 0;
while(i != s.size() && flag == 0)
{
flag = 1;
for(string_size k = 0; k < seperator.size(); k++)
{
if(s[i] == seperator[k])
{
i++;
flag = 0;
break;
}
}
}
//找到又一个分隔符,将两个分隔符之间的字符串取出;
flag = 0;
string_size j = i;
while(j != s.size() && flag == 0)
{
for(string_size k = 0; k < seperator.size(); k++)
{
if(s[j] == seperator[k])
{
flag = 1;
break;
}
}
if(flag == 0)
j++;
}
if(i != j)
{
result.push_back(s.substr(i, j-i));
i = j;
}
}
return result;
}
//读取信息.
static void ReadInformation(const std::string path)
{
std::ifstream fin(path.c_str());
if(fin.is_open() == false)
{
std::cout <<"Read File Failed!!!"<<std::endl;
return ;
}
std::string line;
while(std::getline(fin,line))
{
std::vector<std::string> results;
results = splitString(line,",");
double x = stringToNum<double>(results[0]);
double y = stringToNum<double>(results[1]);
double theta = stringToNum<double>(results[2]);
std::cout<<x<<","<<y<<","<<theta<<std::endl;
}
fin.close();
std::cout <<"Read Pose Good!!!"<<std::endl;
}
二、fstream生成txt文件
#include <fstream>
ofstream fout("fout.txt",ios::out);
if (fout.is_open())
{
fout << "aaaaaaa\n";
fout << "bbbbbbb\n";
fout.close();
}