boost::Program_options如何在值中支持散列字符

boost::Program_options How to support hash character in a value?

本文关键字:支持 字符 Program options boost      更新时间:2023-10-16

我正在尝试在配置文件的值中使用散列符号('#')。

我的用例是一个音乐程序,其中的值给出吉他乐谱的调音。因此,在值中支持'#'是强制性的,并且不支持任何解决方案,不像平坦值,可以使用'b'来模拟。

我试过以下语法:

tuning.1=d#
tuning.1=d#
tuning.1=d##

在所有这些情况下,键tuning.1接收值d,这当然不是目的。

是否有可能在一个键的值中有一个哈希符号?我似乎在boost文档或在线上找不到任何关于它的信息。还是应该编写一个自定义解析器?

我不认为你可以改变boost::program_options如何解析值,因为文档说The # character introduces a comment that spans until the end of the line .

但是,您可以在解析配置文件时使用boost::iostreams中的自定义过滤器将您的哈希字符转换为另一个哈希字符。请参阅有关过滤器使用和输入过滤器的文档。下面是我写的一个非常基本的代码,用@替换#:

#include <boost/iostreams/filtering_stream.hpp>
struct escape_hash_filter: public boost::iostreams::input_filter
{
  template <typename Source>
  int get (Source& src)
  {
    int c = boost::iostreams::get (src);
    if ((c == EOF) or (c == boost::iostreams::WOULD_BLOCK))
      return c;
    return ((c == '#')? '@': c;
  }
};

使用示例:

std::ifstream in {"example.cfg"};
boost::iostreams::filtering_istream escaped_in;
escaped_in.push (escape_hash_filter {});
escaped_in.push (in);
po::store (po::parse_config_file (escaped_in, desc), vm);