boost-tuples - 从 boost::tuples::tuple 中检索字符串
问题描述
阅读https://www.boost.org/doc/libs/1_67_0/libs/tuple/doc/html/tuple_users_guide.html上的文章后 ,以下注释对我来说是个问题。请注意,使用 std::string 或 C 样式字符串元素提取元组通常不起作用,因为流式元组表示可能无法明确解析。我应该使用什么类型将字符串从流中明确解析为元组?
从元组中检索 std::string 时,该字符串由空格分隔。这是不希望的!设置分隔符,例如数字符号 (#) 没有帮助。
// typedef tuple
typedef std::string td_current_gmt, td_remote_endpoint,
td_request, td_response, td_elapsed_time;
typedef boost::tuples::tuple<td_current_gmt, td_remote_endpoint,
td_request, td_response, td_elapsed_time> tuple_logging;
// store in tuple
tuple_logging tl{ current_gmt, remote_endpoint,
request, response, elapsed_time };
// write tuple to file
tl = boost::tuples::make_tuple(current_gmt, remote_endpoint,
request, response, elapsed_time);
boost::filesystem::path p = { "logging" };
boost::filesystem::ofstream ofs{ p };
ofs << /*boost::tuples::set_delimiter('#') <<*/ tl;
ofs.close();
// read tuple from file
tuple_logging tlin{ current_gmt, remote_endpoint,
request, response, elapsed_time };
boost::filesystem::ifstream ifs{ p };
//ifs >> boost::tuples::set_delimiter('#');
ifs >> tlin;
输出是 (Fri, 16 Aug 2019 06:28:05) 但实际上它必须是 (Fri, 16 Aug 2019 06:28:05 GMT 192.168.178.14:52832 TRACE / HTTP/1.1 HTTP/1.1 200 OK 8.936800)
解决方案
这是代码。
void parse_logfile(
boost::filesystem::ifstream& ifs,
const boost::filesystem::path& p,
std::vector<tuple_logging>& vector_with_tuples
) { typedef std::string one_line_from_logging;
one_line_from_logging str;
tuple_logging tlin;
// clear vector
vector_with_tuples.clear();
// open log file for reading
ifs.open(p);
// read one line from log file, until eof
while (std::getline(ifs, str))
{
size_t sBegin = 0, sEnd = 0;
// 1
// first character on a line is '(',
// start at sBegin = 1
sBegin = sEnd + 1;
sEnd = str.find('#', sBegin);
std::string current_gmt_ = str.substr(sBegin, sEnd - sBegin);
// 2
sBegin = sEnd + 1;
sEnd = str.find('#', sBegin);
std::string remote_endpoint_ = str.substr(sBegin, sEnd - sBegin);
// 3
sBegin = sEnd + 1;
sEnd = str.find('#', sBegin);
std::string request_ = str.substr(sBegin, sEnd - sBegin);
// 4
sBegin = sEnd + 1;
sEnd = str.find('#', sBegin);
std::string response_ = str.substr(sBegin, sEnd - sBegin);
// 5
sBegin = sEnd + 1;
// last character on a line is ')'
sEnd = str.find(')', sBegin);
std::string elapsed_time_ = str.substr(sBegin, sEnd - sBegin);
// create tuple from parsed log data out of file
tlin = boost::tuples::make_tuple(
current_gmt_,
remote_endpoint_,
request_,
response_,
elapsed_time_
);
// set tuple into vector
vector_with_tuples.push_back(tlin);
}
// close log file
ifs.close();
}
推荐阅读
- python - 在 Python 3.9 的类中使用列表时出错
- php - 在子包中构建 laravel 就绪的 ORM 模型?(什么依赖?)
- python - pca-valueError:无法将字符串转换为浮点数:'finalized'
- android - 我想为片段编写一个通知按钮,但我的代码有一些问题
- python - 使用 twinx() 时 X 轴日期范围发生变化
- c# - 如何从 ASP.NET MVC 5 中的不同控制器(站点范围)访问 cookie?
- angular - 在有角度的前端应用程序上隐藏我的私钥 RSA
- elasticsearch - 多行日志的顺序不正确
- rust - 在 Rust 中使用泛型、特征别名和构造函数
- azure-devops - 如果我是发起该部署的人,则自动授予我对发布的批准