您的位置:首页 > 编程语言 > C语言/C++

C++ sstream 从文件中读取参数

2017-09-22 10:44 253 查看

头文件

#include <sstream>


从一个TXT中逐行读取参数

一个简单的例子

txt文件:

#’#’is comment

#Parameter

SAMPLE_VIDEO_PATH ../../../测试视频/

#

SOURCE_VIDEO_PATH ../../../FFOutput/

#

INDEX_NAME test_video_duplicate

代码如下:

#include <stdexcept>
#include <sstream>
#include <fstream>

static std::string INDEX_NAME;
static std::string SAMPLE_VIDEO_PATH;
static std::string SOURCE_VIDEO_PATH;

static void readParameter(const char* filename)
{
std::stringstream buffer;
std::string line;
std::string paramName;
std::string paramValuestr;

std::ifstream fin(filename);
if (!fin.good())
{
std::string msg("parameters file not found");
msg.append(filename);
throw std::runtime_error(msg);
}
while (fin.good())
{
getline(fin,line);
if(line[0] != '#')
{
buffer.clear();//before multiple convertion ,clear() is necessary !
buffer << line;
buffer >> paramName;

if(paramName.compare("SAMPLE_VIDEO_PATH") == 0)
{
buffer >>paramValuestr;
SAMPLE_VIDEO_PATH = paramValuestr;
}
else if(paramName.compare("SOURCE_VIDEO_PATH") == 0)
{
buffer >>paramValuestr;
SOURCE_VIDEO_PATH = paramValuestr;
}
else if(paramName.compare("INDEX_NAME") == 0)
{
buffer >>paramValuestr;
INDEX_NAME = paramValuestr;
}
else
throw std::runtime_error(std::string("unknown parameter"));

}

}

fin.close();

}


注意事项

反复进行格式转换的时候,应当有对stringstream的clear()操作,非常非常重要~
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  c++ sstream 流式读取