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 
#include 
#include 
#include 
#include 

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();

}

你可能感兴趣的:(C++)