C++读取.ini文件实例

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种方法

  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

明月醉窗台

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值