C++读取.ini文件实例
对.ini文件通过读取.txt的方式进行每行读取,然后进行字符串操作
1.读取.ini
//读取文件点坐标
std::vector<cv::Point3f> readini(const std::string& fileName)
{
std::vector<cv::Point3f>points;
//读取数据,0-文件第一行,>0:三维坐标字符串
std::vector<std::string>data;
std::ifstream fin;
//打开文本文件
fin.open(fileName.c_str(), std::ios::in);
//判断文本文件是否成功打开
if (!fin.is_open())
{
std::cout << "Open file failed!" << std::endl;
return points;
}
else
std::cout << "Open file sucess!" << std::endl;
std::string section_name;
while (!fin.eof())//判断读取是否到达文件末尾
{
std::string str_txt;
std::getline(fin, str_txt);//将一整行数据作为一个字符串读入
if (!str_txt.empty())//判断该行数据是否为空
{
if (str_txt[0] == '#')//如果该行是以#开始,则是注释行,跳过
continue;
//获取节的名称
if (str_txt[0] == '[')
{
section_name = str_txt.substr(1, str_txt.length() - 2);
data.push_back(section_name);
continue;
}
else
{
int pos = str_txt.find("=");//如果该行的数据格式不对则跳过
if (pos == -1)
continue;
std::string key = str_txt.substr(0, pos);
std::string value = str_txt.substr(pos + 1, str_txt.length());
data.push_back(value);
}
}
if (!fin.good())
break;
}
fin.close();
cv::Point3f p;
for (int i = 1; i < data.size(); ++i)
{
std::vector<std::string>strs = str_split(data[i], ',');//需要设为单引号!!!
if (strs.size() == 3)
{
p.x = std::stof(strs[0]);
p.y = std::stof(strs[1]);
p.z = std::stof(strs[2]);
points.push_back(p);
std::cout << p << std::endl;
}
else {
continue;
}
}
return points;
}
2.字符串分割
//字符串分割
std::vector<std::string> str_split(const std::string& str, const char split)
{
std::vector<std::string>res;
if (str == "") return res;
//在字符串末尾也加入分隔符,方便截取最后一段
std::string strs = str + split;
size_t pos = strs.find(split);
// 若找不到内容则字符串搜索函数返回 npos
while (pos != strs.npos)
{
std::string temp = strs.substr(0, pos);
res.push_back(temp);
//去掉已分割的字符串,在剩下的字符串中进行分割
strs = strs.substr(pos + 1, strs.size());
pos = strs.find(split);
}
return res;
}
效果:
#include<iostream>
#include<fstream>
//测试求取点集中心
std::string fileName = "./file/KeyPoint_R_pts.ini";
std::vector<cv::Point3f>points0 = readini(fileName);
搞定!
参考:
1. C++简单文本读取(txt,csv,ini)
2. C++中string如何实现字符串分割函数split()——4种方法