1

I am trying to have the hash sign ('#') in a value of a configuration file.

My use case is a music program in which the values give the tuning of a guitar score. Therefore, supporting '#' in the values is mandatory and supports no workaround, unlike flats, which can be simulated using a 'b'.

I have tried the following syntaxes:

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

In all those cases, the key tuning.1 receives the value d, which is of course not the intention.

Is it possible to have a hash sign in the value of a key? I can't seem to find anything about it in the boost documentation or online. Or should I resort to writing a custom parser?

AbVog
  • 1,435
  • 22
  • 35

1 Answers1

1

I don't think you can change how boost::program_options parses the values, because the documentation says that The # character introduces a comment that spans until the end of the line.

However, you could transform your hash character into another one when the configuration file is parsed, using a custom filter from boost::iostreams. See the documentation regarding filter usage and input filters. Here is a very basic I wrote that replaces # with @:

#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;
  }
};

Example of how to use it:

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);
piwi
  • 5,136
  • 2
  • 24
  • 48
  • You'd probably also want to convert an @ in a #, so that the @ sign can then be used as a comment character. – MSalters Aug 11 '15 at 08:06
  • @MSalters True! Another possibility would be to not convert `#` if all preceding characters of the current line are spaces. – piwi Aug 12 '15 at 21:23
  • @piwi: it's working like a charm. I have adapted the code of the struct to follow your suggestion in the comment, ie to only convert when all preceding characters of the current line are spaces. By doing so, existing configuration files are left untouched and changes to the code are limited to taking sharps into account when reading the tuning. Excellent. Thanks. – AbVog Aug 14 '15 at 14:09