将参数值从主函数中分离,以便可以在不重新编译代码的情况下修改值大小,我们可以使用配置文件来传递值。这样,我们可以在不修改源代码的情况下,通过修改配置文件中提供新的参数值来更改。
1.创建一个文本文件,用于参数值。例如,创建一个名为config.txt的文件。
2.在config.txt文件中,将参数值写入文件中。每个配置占一行,并使用适当的标识符或注释来标识每个值。注意等号前后不要加空格
# config配置
num1=100
num2=60
num3=200
num4=30
```
3.在代码中使用文件读取操作来读取配置文件中的参数值。
#include <fstream>
#include <iostream>
#include <string>
using namespace std;
int main() {
if (!configFile)
{
std::cout << "Failed to open config file." << std::endl;
return -1;
}else
{
std::cout << "open config file." << std::endl;
}
std::string line;
double Scene_Error_Threshold = 0;
double Scene_Error_Threshold_min = 0;
double Scene_Error_Threshold_max = 0;
double Scene_Variance_max = 0;
// 逐行读取配置文件
while (std::getline(configFile, line))
{
// 解析每行
size_t delimiterPos = line.find('=');
if (delimiterPos == std::string::npos)//没有匹配到=
{
continue; // 忽略无效行
}
std::string key = line.substr(0, delimiterPos);//等号前为键
std::string valueStr = line.substr(delimiterPos + 1);//等号后为键值
double value = std::stod(valueStr);//将有效字符串转化为double类型
// 根据键名设置对应的阈值变量
if (key == "num1")
{
num1 = value;
}
else if (key == "num2")
{
num2 = value;
}
else if (key == "num3")
{
num3;
}
else if (key == "num4")
{
num4;
}
}
configFile.close(); // 关闭配置文件 可以释放资源
std::cout << "num1: " << num1 << std::endl;
std::cout << "num2: " << num2 << std::endl;
std::cout << "num3: " << num3 << std::endl;
std::cout << "num4: " << num4 << std::endl;
//验证是否正确读取
return 0;
}
如果想在解析配置文件时忽略键和值字符串中的空格,可以使用 std::trim() 函数(需要包含 <algorithm> 头文件)来去除字符串中的空格。
std::string key = line.substr(0, delimiterPos);
std::string valueStr = line.substr(delimiterPos + 1);
// 去除键和值字符串中的空格
key.erase(std::remove(key.begin(), key.end(), ' '), key.end());
valueStr.erase(std::remove(valueStr.begin(), valueStr.end(), ' '), valueStr.end());