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++中ifstream一次读取整个文件
- 转自【北漂民工】C++文件读取操作的全部函数讲解fstream(ofstream/ifstream)
- C++读取写入.txt文件(ifstream/ofstream)—读取指定行,修改指定行,复制文件,清除文件,统计文件行数
- c++中ifstream一次读取整个文件
- c++使用getline和ifstream读取文件
- C++读取写入.txt文件(ifstream/ofstream)—读取指定行,修改指定行,复制文件,清除文件,统计文件行数
- c++中ifstream一次读取整个文件
- c++中ifstream一次读取整个文件
- C++中利用文件输入对象(即ifstream对象)来读取文本文件中带空格的字符串以及混合输入数字与字符串
- c++ std::ifstream 读取文件不完整? 是不是忘记了ios_base::binary
- C++ 读取配置文件的 ofstream和ifstream详细用法
- c++中ifstream一次读取整个文件
- c++中ifstream一次读取整个文件
- c++中如何利用vector fstream进行文件的读取
- c++文件读取之write参数理解
- C++读取文件中的汉字,wifstream,wstring的使用
- C++ 格式读取文件中的参数
- c++中ifstream一次读取整个文件
- c++使用getline和ifstream读取文件
- C++fstream,ifstream和outstream读取文件最后一行注意