hyperrealm / libconfig

C/C++ library for processing configuration files
https://hyperrealm.github.io/libconfig/
GNU Lesser General Public License v2.1
1.1k stars 360 forks source link

Integer parsed as double produces error #156

Closed floli closed 4 years ago

floli commented 4 years ago

Hello,

I have experienced that a value like myvalue = 2 in the config file, when parsed as a double produces an error, i.e., return code of 0.

Example code:

#include <iostream>
#include <libconfig.h++>

using namespace std;
using namespace libconfig;

int main()
{
  cout << "Version " << LIBCONFIGXX_VER_MAJOR << "."
                     << LIBCONFIGXX_VER_MINOR << "."
                     << LIBCONFIGXX_VER_REVISION << endl;

  double myvalue = 0;
  int myIvalue = 0;

  Config config;
  config.readFile("vtd_plugin_config.cfg");
  Setting& setting = config.getRoot()["mygroup"];

  bool status = setting.lookupValue("myvalue", myvalue);
  cout << "Found double value = " << myvalue << " with status " << status << endl;

  status = setting.lookupValue("myvalue", myIvalue);
  cout << "Found integer value = " << myIvalue << " with status " << status << endl;
  return 0;
}

Example config:

mygroup = {
        myvalue = 10
}

gives output

% clang++ -std=c++11 -I $HOME/software/libconfig/include -L $HOME/software/libconfig/lib -lconfig++ test.cpp && LD_LIBRARY_PATH=$HOME/software/libconfig/lib ./a.out
Version 1.7.0
Found double value = 0 with status 0
Found integer value = 10 with status 1

(version is 1.7.2, just downloaded and compiled)

My expectation when reading in a value like 10 is a result of 10.0.

thomastrapp commented 4 years ago

You can enable this behavior with the option Config::OptionAutoConvert, like this:

Config config;
config.setOptions(Config::OptionAutoConvert);

Turning this option on enables number auto-conversion for the configuration. When this feature is enabled, an attempt to retrieve a floating point setting’s value into an integer (or vice versa), or store an integer to a floating point setting’s value (or vice versa) will cause the library to silently perform the necessary conversion (possibly leading to loss of data), rather than reporting failure. By default this option is turned off.

floli commented 4 years ago

Ok, thanks!