C++ 格式读取文件中的参数

C++中格式读取文件中的参数

参数文件parameters.txt大概是这样的形式
#Parameters
#sampling rate of frames(reference value:2-10)
samplingRate 2

#mode of feature extraction
videoSampleFeatureMode 13
videoSearchingFeatureMode 10
#7-12(general: 10)
#/home/lumeiqi/projects/newVideoRetrieval attention the enter key
videoPath ../testvideo/test.mp4

其中#开头行代表注释,参数值有整数有字符串,记录读取代码,备忘
代码如下:

#include "Parameters.h"
#include <fstream>
#include <string>
#include <sstream>
#include <stdexcept>
#include <iostream>

int Parameters::readParameters(const char *filename)
{
    /*char buffer[2048];
    char paramName[100];
    int paramValue = 0;
    char paramValuestr[100];*/
    //避免使用C语言风格的字符数组,使用string,能省去很多问题
    //使用stringstream和ifstream做流式读取会简单很多

    stringstream buffer;
    string line;
    string paramName;
    int paramValue = 0;
    string paramValuestr;

    ifstream fin(filename);
    if (!fin.good())
    {
        string msg("parameters file not found");
        msg.append(filename);
        throw runtime_error(msg);
    }
    while (fin.good())
    {
        getline(fin,line);
        if(line[0] != '#')
        {
          buffer << line;//order is important
          buffer >> paramName;
          if(paramName.compare("samplingRate") == 0)
          {
         buffer >> paramValue;
         samplingRate = paramValue;
          }
          else if(paramName.compare("videoSampleFeatureMode") == 0)
          {
         buffer >> paramValue;
         videoSampleFeatureMode = paramValue;
          }
          else if(paramName.compare("videoSearchingFeatureMode") == 0)
          {
         buffer >> paramValue;
         videoSearchingFeatureMode = paramValue;
          }
          else if(paramName.compare("videoPath") == 0)
          {
         buffer >>paramValuestr;
         videoPath = paramValuestr;
          }
          else{
            throw runtime_error(string("unknown parameter: ").append(paramName));
        }

        }

      }
    fin.close();

}
  • 0
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值