Parsing std::chrono::duration with boost::program_options - c++

I'm trying to parse the command line using boost::program_options (boost version 1.80.0, and Apple clang 14.0.0 on arm64-apple-darwin22.2.0) in order to read a std::chrono::duration<int> object formatted as 12h34m56s. According to the documentation, one is required to overload the validate function as follows in my code below.
#include <boost/program_options.hpp>
#include <iostream>
namespace po = boost::program_options;
using Duration = std::chrono::duration<int>;
inline void validate(boost::any &value, const std::vector<std::string> &values, Duration* target_type) {
using namespace std::chrono_literals;
try {
po::validators::check_first_occurrence(value);
auto duration_str = po::validators::get_single_string(values);
Duration duration = Duration::zero();
std::string::size_type i = 0;
while (i < duration_str.size()) {
std::string::size_type j = i;
while (j < duration_str.size() && std::isdigit(duration_str[j])) {
++j;
}
int v = std::stoi(duration_str.substr(i, j - i));
i = j;
if (i < duration_str.size() && duration_str[i] == 'h') {
duration += v * 1h;
++i;
} else if (i < duration_str.size() && duration_str[i] == 'm') {
duration += v * 1min;
++i;
} else if (i < duration_str.size() && duration_str[i] == 's') {
duration += v * 1s;
++i;
}
}
value = boost::any(duration);
} catch (...) {
throw po::invalid_option_value("Invalid duration");
}
}
int main(int ac, char *av[])
{
try
{
po::options_description desc("Allowed options");
desc.add_options()
("help,h", "produce a help screen")
("duration,d", po::value<Duration>(), "duration in 12h34m56s format")
;
po::variables_map vm;
po::store(po::parse_command_line(ac, av, desc), vm);
if (vm.count("help"))
{
std::cout << desc;
return 0;
}
if (vm.count("duration"))
{
std::cout << "The duration is \""
<< vm["duration"].as<Duration>().count()
<< "\"\n";
}
}
catch (std::exception& e)
{
std::cout << e.what() << "\n";
}
return 0;
}
However, this fails to compile, and the compiler reports that:
/opt/homebrew/include/boost/lexical_cast/detail/converter_lexical.hpp:243:13: error: static_assert failed due to requirement 'has_right_shift<std::istream, std::chrono::duration<int, std::ratio<1, 1>>, boost::binary_op_detail::dont_care>::value || boost::has_right_shift<std::wistream, std::chrono::duration<int, std::ratio<1, 1>>, boost::binary_op_detail::dont_care>::value' "Target type is neither std::istream`able nor std::wistream`able"
BOOST_STATIC_ASSERT_MSG((result_t::value || boost::has_right_shift<std::basic_istream<wchar_t>, T >::value),
^ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
I've also tried implementing the istream operator>> as well as overloading boost::lexical_cast for the std::chrono::duration<int> class but with no success. What am I missing here?
Edit after #rubenvb 's answer
I tried making std::chrono::duration<int> both std::istream and std::wistream able, but again to no avail. Note that std::chrono::from_stream is not available on my compiler.
template <typename String>
inline Duration parseDuration(const String& duration_str)
{
using namespace std::chrono_literals;
Duration duration;
typename String::size_type i = 0;
while (i < duration_str.size()) {
std::wstring::size_type j = i;
while (j < duration_str.size() && std::iswdigit(duration_str[j])) {
++j;
}
int v = std::stoi(duration_str.substr(i, j - i));
i = j;
if (i < duration_str.size() && duration_str[i] == 'h') {
duration += v * 1h;
++i;
} else if (i < duration_str.size() && duration_str[i] == 'm') {
duration += v * 1min;
++i;
} else if (i < duration_str.size() && duration_str[i] == 's') {
duration += v * 1s;
++i;
}
}
return duration;
}
inline std::wistream& operator>>(std::wistream& is, Duration& duration) {
std::wstring duration_str;
is >> duration_str;
duration = parseDuration(duration_str);
return is;
}
inline std::istream& operator>>(std::istream& is, Duration& duration) {
std::string duration_str;
is >> duration_str;
duration = parseDuration(duration_str);
return is;
}

You can overload operator>>. Keep in mind it relies on ADL, though, so it needs to be in std::chrono namespace.
However, that's icky, as it will either lead to surprises to other code or even risk ODR violations across TUs.
Instead, notice that validate also leverages ADL. Finally note that your overload can be in any of the associated namespaces: std (due to vector and basic_string), std::chrono (due to duration) but also boost(due toany`)!This vastly reduces the potential to interfere with current or future standard symbols.
So here's fixed:
Live On Coliru
#include <boost/program_options.hpp>
#include <chrono>
#include <iostream>
namespace po = boost::program_options;
using Duration = std::chrono::duration<int>;
namespace boost {
template <class CharT>
void validate(boost::any& value, std::vector<std::basic_string<CharT>> const& values, Duration*, int) {
using namespace std::chrono_literals;
try {
po::validators::check_first_occurrence(value);
auto duration_str = po::validators::get_single_string(values);
Duration duration = Duration::zero();
std::string::size_type i = 0;
while (i < duration_str.size()) {
std::string::size_type j = i;
while (j < duration_str.size() && std::isdigit(duration_str[j])) {
++j;
}
int v = std::stoi(duration_str.substr(i, j - i));
i = j;
if (i < duration_str.size() && duration_str[i] == 'h') {
duration += v * 1h;
++i;
} else if (i < duration_str.size() && duration_str[i] == 'm') {
duration += v * 1min;
++i;
} else if (i < duration_str.size() && duration_str[i] == 's') {
duration += v * 1s;
++i;
}
}
value = boost::any(duration);
} catch (...) {
throw po::invalid_option_value("Invalid duration");
}
}
} // namespace boost
int main(int argc, char** argv) {
po::options_description opts("Demo");
opts.add_options() //
("duration,d", po::value<Duration>(), "test") //
;
std::cout << opts << "\n";
po::variables_map vm;
store(po::parse_command_line(argc, argv, opts), vm);
if (vm.contains("duration")) {
std::cout << "Value: " << vm["duration"].as<Duration>() << "\n";
}
}
Prints e.g.
g++ -std=c++20 -O2 -Wall -pedantic -pthread main.cpp -lboost_program_options
./a.out -d 3m
Demo:
-d [ --duration ] arg test
Value: 180s

It seems the error you're getting is that you don't have an operator>> defined for std::wistream (i.e. the std::basic_istream<wchar_t> in your error message).
Additionally, you can extract a std::chrono::duration from a stream using from_stream. So that can easily replace your manual parsing code.

I think a better approach is to add a specialization of lexical_cast or try_lexical_convert method from boost conversion library.
The code in program options calls internally boost::lexical_cast<> (from the conversion lib) to convert between text and the desired type, and the cast uses internally try_lexical_convert.
This way you don't have to repeat the boilerplate validate code (i.e., things like check_first_occurrence and get_single_string) every time you need to support yet another type.
Also, if you want to set default value and output options_description, then you also have to add conversion from duration to string.
Have a look at an example code that I use to set timeouts in a config file (hence it supports only number followed by us/ms/s units):
#include <boost/program_options.hpp>
#include <chrono>
#include <string>
#include <cstdlib>
#include <regex>
namespace boost::conversion::detail {
template<>
bool try_lexical_convert<std::chrono::microseconds, std::string>(const std::string& in, std::chrono::microseconds& out){
std::smatch m;
if(!std::regex_match(in, m, std::regex(R"((\d+(?:\.\d*)?)\s*([um]?)s)",std::regex_constants::icase)))
return false;
std::string number = m.str(1);
std::string unit = m.str(2);
char * end;
double count = std::strtod(number.data(), &end);
if(number.data() + number.length() != end)
return false;
if (unit.empty()) count *= 1e6;
else if(unit == "m" ) count *= 1e3;
else if(unit != "u" ) assert(false);
out = std::chrono::duration_cast<std::chrono::microseconds>(std::chrono::duration<double, std::micro>(count));
return true;
}
template<>
bool try_lexical_convert<std::string, std::chrono::microseconds>(const std::chrono::microseconds& in, std::string& out){
out = std::to_string(in.count()) + "us";
return true;
}
}
#include <iostream>
int main(int argc, char *argv[]) {
using namespace std::literals;
using namespace boost::program_options;
std::chrono::microseconds us;
options_description opts;
opts.add_options()("time,t", value(&us)->default_value(10ms), "some time");
std::cout << opts;
variables_map vm;
store(parse_command_line(argc, argv, opts), vm);
notify(vm);
std::cout << us.count() << "us\n" << us.count()/1e3 << "ms\n" << us.count()/1e6 << "s" << std::endl;
return 0;
}
(this should compile with C++17, and with minor changes it should work with C++11 as well)

Related

Implementing an alphabet in C++

I'm making a code for cipher that reads alphabet in it's binary code. Is there a way to implement custom alphabet (not using ASCII)? For example alphabet={a,b,c,d,e,...,z,],[,.,..., ,-} and for each character there's a number 0,1,...,63. So, the bijetion will be from element of alphabet to 6 bit number.
How to make this implementation using simple functions in C++? I tried to make a strings length 1 and corresponding number using if statements and then plug them into .txt file, but it didn't work out.
string str1, ..., str63;
string sometext;
str1 = 'a';
// ...
cin >> sometext;
int k;
k = sometext.length();
string res;
ofstream out;
out.open("cipher.txt");
for (int i = 0; i < k; i++) {
res = sometext.substr(i, 1);
if (res == str1) {
res = '000000';
}
// ...
if (res == str63) {
res = '111111';
}
out << res;
}
I made a simple class Alphabet achieving your task. It uses std::unordered_map to store mapping between characters and binary representation, and uses this mapping to convert between those two representations. Also it computes binary representation. Class can be given any alphabet.
For testing I do two conversions between char and binary and output results to console. If requested values are out of range then std::exception is thrown.
Try it online!
#include <string>
#include <unordered_map>
#include <cmath>
#include <stdexcept>
#include <iostream>
class Alphabet {
public:
Alphabet(std::string const & _chars)
: chars(_chars) {
size_t num_bits = std::ceil(std::log(std::max(size_t(1), chars.size()))
/ std::log(2) - 1e-6);
for (size_t i = 0; i < chars.size(); ++i) {
std::string bin;
for (ptrdiff_t j = num_bits - 1; j >= 0; --j)
bin += i & (1 << j) ? "1" : "0";
c2b[chars[i]] = bin;
b2c[bin] = chars[i];
}
}
std::string ToBin(char c) const {
auto it = c2b.find(c);
if (it == c2b.end())
throw std::runtime_error("Character '" +
std::string(1, c) + "' not in alphabet!");
return it->second;
}
char ToChar(std::string const & bin) const {
auto it = b2c.find(bin);
if (it == b2c.end())
throw std::runtime_error("Binary '" + bin + "' is out of range!");
return it->second;
}
std::string const & Chars() const {
return chars;
}
private:
std::string chars;
std::unordered_map<char, std::string> c2b;
std::unordered_map<std::string, char> b2c;
};
int main() {
try {
Alphabet alph("abcdef{}123");
std::cout << alph.ToBin('f') << std::endl;
std::cout << alph.ToChar("0011") << std::endl;
std::cout << alph.Chars() << std::endl;
return 0;
} catch (std::exception const & ex) {
std::cout << "Exception: " << ex.what() << std::endl;
return -1;
}
}
Output:
0101
d
abcdef{}123

Avoiding or improving brute force method: Counting character repetition from all words in a dictionary text file

I wrote this utility function that will take the contents of a alpha dictionary file and will add up the repetition count of each letter or character of the alphabet.
This is what I have so far:
#include <algorithm>
#include <fstream>
#include <iostream>
#include <map>
#include <string>
#include <vector>
// this function just generates a map of each of the alphabet's
// character position within the alphabet.
void initCharIndexMap( std::map<unsigned, char>& index ) {
char c = 'a';
for ( unsigned i = 1; i < 27; i++ ) {
index[i] = c;
c++;
}
}
void countCharacterRepetition( std::vector<std::string>& words, const std::map<unsigned, char> index, std::map<char, unsigned>& weights ) {
unsigned count = 0;
for ( auto& s : words ) {
std::transform(s.begin(), s.end(), s.begin(), ::tolower );
for ( std::size_t i = 0; i < s.length(); i++ ) {
using It = std::map<unsigned, char>::const_iterator;
for ( It it = index.cbegin(); it != index.cend(); ++it ) {
if ( s[i] == it->second ) {
count++;
weights[it->second] += count;
}
count = 0;
}
}
}
}
int main() {
std::vector<std::string> words;
std::string line;
std::ifstream file;
file.open( "words_alpha.txt" );
while( std::getline( file, line )
words.push_back(line);
std::map<unsigned, char> index;
initCharIndexMap(index);
std::map<char, unsigned> weights;
countCharRepetition(words, index, weights);
for (auto& w : weights)
std::cout << w.first << ' ' << w.second << '\n';
return EXIT_SUCCESS;
}
It gives me this output which appears to be valid at first glance:
a 295794
b 63940
c 152980
d 113190
e 376455
f 39238
g 82627
h 92369
i 313008
j 5456
k 26814
l 194915
m 105208
n 251435
o 251596
p 113662
q 5883
r 246141
s 250284
t 230895
u 131495
v 33075
w 22407
x 10493
y 70578
z 14757
The dictionary text file that I am using can be found from this github page.
This appears to be working. It took about 3 minutes to process on my current machine which isn't horrible, however, this seems like a brute force approach. Is there a more efficient way of doing a task like this?
If you're just counting how many times each character appears, then all you need is this:
int frequency[26] = {};
for (auto const& str : words) {
for (int i=0; i<str.size(); i++) {
frequency[tolower(str[i]) - 'a']++;
}
}
for (int i=0; i<26; i++) {
cout << char(i + 'a') << " " << frequency[i] << endl;
}
If you want to include upper and lowercase characters, change the array size to 90, remove the tolower call, and change your loop so that it prints only if i is between a and z or A and Z.
If you are just going for performance, I would say you still have to read in the file char by char - but I think all the searching is processing that could be optimised.
I would say the following pseudo code should be faster (I'll try and knock up an example later):
void read_dictionary(char *fileName)
{
// Pre-sized array (faster access)
std::array<int, 26> alphabet_count = {0};
// Open the file
FILE *file = fopen(fileName, "r");
if (file == NULL)
return; //could not open file
// Read through the file
char c;
while ((c = fgetc(file)) != EOF)
{
// If it is a letter a-z
if ( ((c >= 'a') && (c <= 'z')) ||
{
// Increment the array value for that letter
++alphabet_count[c - 'a'];
}
// else if letter A-Z
else if ( ((c >= 'A') && (c <= 'Z')) ||
{
// Increment the array value for that letter
++alphabet_count[c - 'A'];
}
}
}
The point here is that we are not searching for matches we are using the char value to index into the array to increment the alphabet letter
All of the aforementioned answers assume continuity between a and z, and history will tell you that is not always the case. A solution doesn't need to assume this, and can still be efficient.
#include <iostream>
#include <fstream>
#include <iterator>
#include <climits>
#include <cctype>
int main(int argc, char *argv[])
{
if (argc < 2)
return EXIT_FAILURE;
unsigned int count[1U << CHAR_BIT] {};
std::ifstream inp(argv[1]);
for (std::istream_iterator<char> it(inp), it_eof; it != it_eof; ++it)
++count[ std::tolower(static_cast<unsigned char>(*it)) ];
for (unsigned i=0; i<(1U << CHAR_BIT); ++i)
{
if (std::isalpha(i) && count[i])
std::cout << static_cast<char>(i) << ' ' << count[i] << '\n';
}
}
Output
[~ user]$ clang++ --std=c++14 -O2 -o main main.cpp
[~ user] time ./main /usr/share/dict/words
a 199554
b 40433
c 103440
d 68191
e 235331
f 24165
g 47094
h 64356
i 201032
j 3167
k 16158
l 130463
m 70680
n 158743
o 170692
p 78163
q 3734
r 160985
s 139542
t 152831
u 87353
v 20177
w 13864
x 6932
y 51681
z 8460
real 0m0.085s
user 0m0.073s
sys 0m0.005s
That would probably be sufficiently fast enough for your application, whatever it is.
#include <array>
#include <fstream>
#include <iostream>
int main()
{
std::ifstream file;
file.open( "words_alpha.txt" );
char c;
std::array<std::size_t, 26> counts {};
while( file >> c)
++counts[c-'a'];
for(char c = 0; c<26;++c)
std::cout<<'('<<c+'a'<<','<<counts[c]<<")\n";
}
Your version keeps track of words unnecessarily: you're simply counting characters in a file. The separation into words and lines doesn't matter. It's also unnecessary to store the words.
You could aim for readable high-level code and write something like this:
// https://github.com/KubaO/stackoverflown/tree/master/questions/letter-count-56498637
#include <cctype>
#include <fstream>
#include <iostream>
#include <iterator>
#include <limits>
#include <utility>
#include <vector>
//*
int main() {
Histogram<char, 'a', 'z'> counts;
std::ifstream file;
file.open("words_alpha.txt");
for (auto ch : make_range<char>(file)) counts.count(tolower(ch));
for (auto c : std::as_const(counts)) std::cout << c.value << ' ' << c.count << '\n';
}
This is the bare minimum of how modern C++ code should look
This requires the Histogram class, and a make_range adapter for input streams. You can't merely implement std::begin and std::end for std::ifstream, because the member end() function takes precedence and interferes (see this answer). The code below is the fragment marked //* above.
template <typename T>
void saturating_inc(T &val) {
if (val < std::numeric_limits<T>::max()) val++;
}
template <typename T, T min, T max>
class Histogram {
using counter_type = unsigned;
using storage_type = std::vector<counter_type>;
storage_type counts;
public:
template <typename U>
void count(U val) {
if (val >= min && val <= max) saturating_inc(counts[size_t(val - min)]);
}
Histogram() : counts(1 + max - min) {}
struct element {
T value;
counter_type count;
};
class const_iterator {
T val;
storage_type::const_iterator it;
public:
const_iterator(T val, storage_type::const_iterator it) : val(val), it(it) {}
const_iterator &operator++() {
++val;
++it;
return *this;
}
bool operator!=(const const_iterator &o) const { return it != o.it; }
element operator*() const { return {val, *it}; }
};
const_iterator begin() const { return {min, counts.begin()}; }
const_iterator end() const { return {0, counts.end()}; }
};
template <class C, class T>
class istream_range {
C &ref;
public:
istream_range(C &ref) : ref(ref) {}
std::istream_iterator<T> begin() { return {ref}; }
std::istream_iterator<T> end() { return {}; }
};
template <class T, class C>
istream_range<C, T> make_range(C &ref) {
return {ref};
}
This concludes the example.

Read/Write inifiles with boost::{program_options,property_tree}

Utilizing boost, I would like to
read options from an inifile, abort if an unknown option is encountered in the inifile and
save them later in another inifile.
The first part can be done with boost::program_options:
try{
inifile_options.add_options()
("ops1.i0", po::value<int>(&p.nx)->default_value(1), "test integer")
;
po::variables_map vm;
po::store(po::parse_config_file(pthfnini, inifile_options), vm);
po::notify(vm);
}
catch(exception& e){
cerr << "error: " << e.what() << "\n";
errorflag=1;
}
To the best of my knowledge writing an inifile is not possible with boost::program_options, but boost::property_tree works:
pt::ptree iniPropTree;
pt::ini_parser::write_ini("./used0.ini",iniPropTree);
Now the question is how can I translate the data stored in the po::variables_map to pt::ptree?
Reading the boost documentation leaves me with the impression that this is not possible. Is the following the only viable way?
iniPropTree.put<int>("ops1.i0",vm["ops1.i0"].as<int>();
It introduces quite a bit of redundancy for my taste. However, reading data into a property tree from the beginning does not seem to support checking for undefined/misspelled options.
Alternatively,is it possible to iterate over the contents of variables_map and somehow infer the corresponding datatype of each element?
The full code is here:
/*
* g++ iniOps_test.cpp -Wall -std=c++11 -O3 -lboost_system -lboost_program_options -o iniOps_test.exe
*
*/
// C++11 & Boost libraries
#include <boost/program_options.hpp> // po::options_description, po::variables_map, ...
#include <boost/property_tree/ptree.hpp> // pt::ptree
#include <boost/property_tree/ini_parser.hpp> // write_ini()
#include <iostream> // cout
#include <fstream> // ofstream, ifstream
// namespaces
namespace po = boost::program_options;
namespace pt = boost::property_tree;
using namespace std;
struct params{
std::string inipthfn;
int i0;
};
void read_inifile(params &p, po::variables_map &vm){
// initialize variables
int errorflag=0;
std::ifstream pthfnini("./testini.ini");
po::options_description inifile_options("Allowed inifile options");
try{
inifile_options.add_options()
("ops1.i0", po::value<int>(&p.i0)->default_value(1), "test integer")
;
;
po::store(po::parse_config_file(pthfnini, inifile_options), vm);
po::notify(vm);
}
catch(exception& e){
cerr << "error: " << e.what() << "\n";
errorflag=1;
}
pthfnini.close();
if(errorflag){ std::cout<<"--- program shutdown due to error in read_inifile ---"<<std::endl; exit(1); }
}
int main(){
params p;
po::variables_map vm;
pt::ptree iniPropTree;
read_inifile(p,vm); // get options from inifile
// ??? conversion from vm -> pt ???
pt::ini_parser::write_ini("./used0.ini",iniPropTree); // save options to used.ini
cout << p.i0 << endl;
return 0;
}
The contents of the inifile "testini.ini" are:
[ops1]
i0=2
There's a conceptual problem here.
Commandline parameters are inherently textual.
Values in the variables-map aren't. The types used are configured in the value-semantics (part of your options-description).
If all your options have the same type, you can "cheat" and hard-code a conversion:
pt::ptree to_ptree(po::variables_map const& vm) {
pt::ptree tree;
for (auto& v : vm) {
if (!v.second.empty() && !v.second.defaulted())
tree.put(v.first, v.second.as<int>());
}
return tree;
}
Which saves:
[ops1]
i0=1
If you need more flexibility, you'd need access to the option descriptions at the very least. This is not the intended use of the library, and you'll probably run into undocumented parts of the implementation soon.
However, reading data into a property tree from the beginning does not seem to support checking for undefined/misspelled options
Well. That's not entirely true. You can make your own parse function that adds the logic. Use Property Tree Translators if you want.
Here's an extended example showing three parameters of varying types to be validated:
enum class restricted { value1, value2 };
struct params {
int i0 = 1;
restricted r1 = restricted::value2;
std::string s2 = "some default";
};
We will want to have a parse function like this:
params read_inifile(std::string filename) {
params p;
pt::ptree tree;
std::ifstream file(filename);
read_ini(file, tree);
p.i0 = tree.get("ops1.i0", 1);
p.r1 = tree.get("ops1.r1", restricted::value2);
p.s2 = tree.get("ops1.s2", "some default");
return p;
}
Streamable Types
To translate and validate the enum you merely need to implement the streaming operators:
static inline std::istream& operator>>(std::istream& is, restricted& r) {
std::string v;
if (is >> std::ws >> v) {
if (boost::iequals("value1", v))
r = restricted::value1;
else if (boost::iequals("value2", v))
r = restricted::value2;
else
throw std::runtime_error("invalid restricted value");
}
return is;
}
static inline std::ostream& operator<<(std::ostream& os, restricted r) {
switch(r) {
case restricted::value1: return os << "value1";
case restricted::value2: return os << "value2";
default: return os << "invalid";
}
}
Custom Translators
Let's imagine that i0 need custom validation. In this example, let's REQUIRE it to be an odd number:
namespace translators {
template <typename T>
struct must_be_odd {
typedef T internal_type;
typedef T external_type;
boost::optional<T> get_value(const std::string& str) const {
if (str.empty()) return boost::none;
T v = boost::lexical_cast<T>(str);
if (v % 2 == 0)
throw std::runtime_error("value must be odd");
return boost::make_optional(v);
}
boost::optional<std::string> put_value(const T& i0) {
assert(i0 % 2); // assert that the value was odd
return boost::lexical_cast<std::string>(i0);
}
};
static const must_be_odd<int> i0;
}
Now we can simply supply the translator (here, acting more like a custom validator like Boost Program Options also has them):
p.i0 = tree.get("ops1.i0", 1, translators::i0);
See it Live On Coliru
Unsupported Options
This is a bit more work. You'll have to iterate the tree checking the resultant paths against a known set. Here's a stab at a reasonably generic implementation of that (which should work correctly with case sensitive trees of any (wide) string type):
template <typename Tree,
typename Path = typename Tree::path_type,
typename Key = typename Path::key_type,
typename Cmp = typename Tree::key_compare>
std::size_t unsupported(Tree const& tree, std::set<Key, Cmp> const& supported, Path prefix = "") {
if (tree.size()) {
std::size_t n = 0;
for (auto& node : tree) {
Path sub = prefix;
sub /= node.first;
n += unsupported(node.second, supported, sub);
}
return n;
} else {
if (!supported.count(prefix.dump()) && tree.template get_value_optional<std::string>())
return 1;
}
return 0;
}
You can use it like this:
if (auto n = unsupported(tree, {"ops1.i0", "ops1.r1", "ops2.s2"})) {
throw std::runtime_error(std::to_string(n) + " unsupported options");
}
Full Demo
Live On Coliru
#include <boost/algorithm/string.hpp>
#include <iostream>
#include <set>
enum class restricted { value1, value2 };
static inline std::istream& operator>>(std::istream& is, restricted& r) {
std::string v;
if (is >> std::ws >> v) {
if (boost::iequals("value1", v))
r = restricted::value1;
else if (boost::iequals("value2", v))
r = restricted::value2;
else
throw std::runtime_error("invalid restricted value");
}
return is;
}
static inline std::ostream& operator<<(std::ostream& os, restricted r) {
switch(r) {
case restricted::value1: return os << "value1";
case restricted::value2: return os << "value2";
default: return os << "invalid";
}
}
struct params {
int i0 = 1;
restricted r1 = restricted::value2;
std::string s2 = "some default";
};
#include <boost/property_tree/ini_parser.hpp>
#include <boost/lexical_cast.hpp>
#include <fstream>
namespace pt = boost::property_tree;
namespace translators {
template <typename T>
struct must_be_odd {
typedef T internal_type;
typedef T external_type;
boost::optional<T> get_value(const std::string& str) const {
if (str.empty()) return boost::none;
T v = boost::lexical_cast<T>(str);
if (v % 2 == 0)
throw std::runtime_error("value must be odd");
return boost::make_optional(v);
}
boost::optional<std::string> put_value(const T& i0) {
assert(i0 % 2); // assert that the value was odd
return boost::lexical_cast<std::string>(i0);
}
};
static const must_be_odd<int> i0;
}
template <typename Tree,
typename Path = typename Tree::path_type,
typename Key = typename Path::key_type,
typename Cmp = typename Tree::key_compare>
std::size_t unsupported(Tree const& tree, std::set<Key, Cmp> const& supported, Path prefix = "") {
if (tree.size()) {
std::size_t n = 0;
for (auto& node : tree) {
Path sub = prefix;
sub /= node.first;
n += unsupported(node.second, supported, sub);
}
return n;
} else {
if (!supported.count(prefix.dump()) && tree.template get_value_optional<std::string>())
return 1;
}
return 0;
}
params read_inifile(std::string filename) {
params p;
try {
pt::ptree tree;
std::ifstream file(filename);
read_ini(file, tree);
p.i0 = tree.get("ops1.i0", 1, translators::i0);
p.r1 = tree.get("ops1.r1", restricted::value2);
p.s2 = tree.get("ops1.s2", "some default");
if (auto n = unsupported(tree, {"ops1.i0", "ops1.r1", "ops2.s2"})) {
throw std::runtime_error(std::to_string(n) + " unsupported options");
}
} catch (std::exception const& e) {
std::cerr << "error: " << e.what() << "\n";
throw std::runtime_error("read_inifile");
}
return p;
}
pt::ptree to_ptree(params const& p) {
pt::ptree tree;
tree.put("ops1.i0", p.i0, translators::i0);
tree.put("ops1.r1", p.r1);
tree.put("ops1.s2", p.s2);
return tree;
}
int main() {
params const p = read_inifile("./testini.ini"); // get options from filename
write_ini("./used0.ini", to_ptree(p)); // save options to used.ini
std::cout << p.i0 << std::endl;
}
For input like
[ops1]
i0=17
i99=oops
[oops1]
also=oops
Prints
error: 2 unsupported options
terminate called after throwing an instance of 'std::runtime_error'
what(): read_inifile
And changing 17 to 18 prints:
error: value must be odd
terminate called after throwing an instance of 'std::runtime_error'
what(): read_inifile
On valid input, used0.ini will be written as expected:
[ops1]
i0=1
r1=value2
s2=some default
After giving this problem some more time, I found a suitable compact solution:
The key is to write a function that translates entries from the variables_map to the propTree depending on their datatype (thx to sehe for putting me on the right track):
void translate_variables_map_to_ptree(po::variables_map &vm, pt::ptree &propTree){
for(po::variables_map::iterator it=vm.begin(); it!=vm.end(); it++){
if( it->second.value().type() == typeid(int) ){ propTree.put<int>(it->first,vm[it->first].as<int>()); }
else if( it->second.value().type() == typeid(float) ){ propTree.put<float>(it->first,vm[it->first].as<float>()); }
else if( it->second.value().type() == typeid(double) ){ propTree.put<double>(it->first,vm[it->first].as<double>()); }
else if( it->second.value().type() == typeid(std::string) ){ propTree.put<std::string>(it->first,vm[it->first].as<std::string>()); }
else if( it->second.value().type() == typeid(size_t) ){ propTree.put<size_t>(it->first,vm[it->first].as<size_t>()); }
else{ printf("Error: unknown datatype. Abort!\n"); exit(EXIT_FAILURE); }
}
}
The full working example writes the correct inifile containing all read info:
/*
* g++ iniOps_test.cpp -Wall -std=c++11 -O3 -lboost_system -lboost_program_options -o iniOps_test.exe
*
*/
// C++11 & Boost libraries
#include <boost/program_options.hpp> // po::options_description, po::variables_map, ...
#include <boost/property_tree/ptree.hpp> // pt::ptree
#include <boost/property_tree/ini_parser.hpp> // write_ini()
#include <iostream> // cout
#include <fstream> // ofstream, ifstream
// namespaces
namespace po = boost::program_options;
namespace pt = boost::property_tree;
using namespace std;
struct params{
std::string s0;
int i0;
};
void read_inifile(params &p, po::variables_map &vm){
// initialize variables
int errorflag=0;
std::ifstream pthfnini("./testini.ini");
po::options_description inifile_options("Allowed inifile options");
try{
inifile_options.add_options()
("ops1.i0", po::value<int>(&p.i0)->default_value(1), "test integer")
("ops1.s0", po::value<std::string>(&p.s0)->default_value("default"), "test string")
;
;
po::store(po::parse_config_file(pthfnini, inifile_options), vm);
po::notify(vm);
}
catch(exception& e){
cerr << "error: " << e.what() << "\n";
errorflag=1;
}
pthfnini.close();
if(errorflag){ std::cout<<"--- program shutdown due to error in read_inifile ---"<<std::endl; exit(1); }
}
void translate_variables_map_to_ptree(po::variables_map &vm, pt::ptree &propTree){
for(po::variables_map::iterator it=vm.begin(); it!=vm.end(); it++){
if( it->second.value().type() == typeid(int) ){ propTree.put<int>(it->first,vm[it->first].as<int>()); }
else if( it->second.value().type() == typeid(float) ){ propTree.put<float>(it->first,vm[it->first].as<float>()); }
else if( it->second.value().type() == typeid(double) ){ propTree.put<double>(it->first,vm[it->first].as<double>()); }
else if( it->second.value().type() == typeid(std::string) ){ propTree.put<std::string>(it->first,vm[it->first].as<std::string>()); }
else if( it->second.value().type() == typeid(size_t) ){ propTree.put<size_t>(it->first,vm[it->first].as<size_t>()); }
else{ printf("Error: unknown datatype. Abort!\n"); exit(EXIT_FAILURE); }
}
}
int main(){
params p;
po::variables_map vm;
pt::ptree iniPropTree;
read_inifile(p,vm); // get options from inifile
translate_variables_map_to_ptree(vm,iniPropTree); // conversion from vm -> pt
pt::ini_parser::write_ini("./used0.ini",iniPropTree); // save options to used.ini
cout << p.i0 << endl;
cout << p.s0 << endl;
return 0;
}
Taking a variables_map vm from reading the commandline, it is also possible to update the values in the property tree (from reading the inifile) with:
string opsName = "ops1.i0"; if(vm.count(opsName)) p.i0 = vm[opsName].as<int>();

Deleting two specific Characters

So I have a little problem, I want to achieve this in C++, but I don't know how to do it:
Given is a string containing random numbers, symbols, and letters:
std::string = "1653gbdtsr362g2v3f3t52bv^hdtvsbjj;hdfuue,9^1dkkns";
Now I'm trying to find all ^ characters, and if those are followed by a number between 0 and 9, delete the ^ and the number, so:
"^1ghhu^7dndn^g"
becomes:
"ghhudndn^g"
I know how to find and replace/erase chars from a string, but I don't know how to check if it's followed by a number in a not hard coded way. Any help is appreciated.
std::string s = "^1ghhu^7dndn^g";
for (int i = 0; i < s.length() - 1; ++i)
{
if (s[i] == '^' && std::isdigit(s[i + 1]))
{
s.erase(i, 2);
--i;
}
}
This needs these includes:
#include <string>
#include <cctype>
I would do it this way:
#include <iostream>
#include <string>
#include <utility>
#include <iterator>
template<class Iter, class OutIter>
OutIter remove_escaped_numbers(Iter first, Iter last, OutIter out) {
for ( ; first != last ; )
{
auto c = *first++;
if (c == '^' && first != last)
{
c = *first++;
if (std::isdigit(c))
continue;
else {
*out++ = '^';
*out++ = c;
}
}
else {
*out++ = c;
}
}
return out;
}
int main()
{
using namespace std::literals;
auto input = "^1ghhu^7dndn^g"s;
auto output = std::string{};
remove_escaped_numbers(input.begin(), input.end(), std::back_inserter(output));
std::cout << output << std::endl;
}
or this way:
#include <iostream>
#include <regex>
int main()
{
using namespace std::literals;
auto input = "^1ghhu^7dndn^g"s;
static const auto repl = std::regex { R"___(\^\d)___" };
auto output = std::regex_replace(input, repl, "");
std::cout << output << std::endl;
}
A solution using std::stringstream, and returning the input string cleared of caret-digit's.
#include <iostream>
#include <sstream>
#include <cctype>
int t404()
{
std::stringstream ss;
std::string inStr("1653gbdtsr362g2v3f3t52bv^hdtvsbjj;hdfuue,9^1dkkns");
for (size_t i = 0; i<inStr.size(); ++i)
{
if(('^' == inStr[i]) && isdigit(inStr[i+1]))
{
i += 1; // skip over caret followed by single digit
}
else
{
ss << inStr[i];
}
}
std::cout << inStr << std::endl; // compare input
std::cout << ss.str() << std::endl; // to results
return 0;
}
Output:
1653gbdtsr362g2v3f3t52bv^hdtvsbjj;hdfuue,9^1dkkns
1653gbdtsr362g2v3f3t52bv^hdtvsbjj;hdfuue,9dkkns
you can simply loop over the string and copy it while skipping the undesired chars. Here is a possible function to do it:
std::string filterString (std::string& s) {
std::string result = "";
std::string::iterator it = s.begin();
char c;
while (it != s.end()) {
if (*it == '^' && it != s.end() && (it + 1) != s.end()) {
c = *(it + 1);
if(c >= '0' && c <= '9') {
it += 2;
continue;
}
}
result.push_back(*it);
++ it;
}
return result;
}
A robust solution would be to use the regex library that C++11 brings in.
std::string input ("1653gbdtsr362g2v3f3t52bv^hdtvsbjj;hdfuue,9^1dkkns");
std::regex rx ("[\\^][\\d]{1}"); // "[\^][\d]{1}"
std::cout << std::regex_replace(input,rx,"woot");
>> 1653gbdtsr362g2v3f3t52bv^hdtvsbjj;hdfuue,9wootdkkns
This locates a "^" character ([\^]) followed by 1 ({1}) digit ([\d]) and replaces all occurances with "woot".
Hope this code can solve your problem:
#include <iostream>
#include <string>
int main()
{
std::string str = "^1ghhu^7dndn^g";
std::string::iterator first, last;
for ( std::string::iterator it=str.begin(); it!=str.end(); ++it)
{
if(*it == '^')
{
first = it;
it++;
while(isdigit(*it))
{
it++;
}
last = it - 1;
if(first != last)
{
if((last + 1) != str.end())
{
str.erase(first, last + 1);
}
else
{
str.erase(first, str.end());
break;
}
}
}
}
std::cout<< str << std::endl;
return 0;
}
The output:
$ ./erase
ghhudndn^g

Compare versions as strings

Comparing version numbers as strings is not so easy...
"1.0.0.9" > "1.0.0.10", but it's not correct.
The obvious way to do it properly is to parse these strings, convert to numbers and compare as numbers.
Is there another way to do it more "elegantly"? For example, boost::string_algo...
I don't see what could be more elegant than just parsing -- but please make use of standard library facilities already in place. Assuming you don't need error checking:
void Parse(int result[4], const std::string& input)
{
std::istringstream parser(input);
parser >> result[0];
for(int idx = 1; idx < 4; idx++)
{
parser.get(); //Skip period
parser >> result[idx];
}
}
bool LessThanVersion(const std::string& a,const std::string& b)
{
int parsedA[4], parsedB[4];
Parse(parsedA, a);
Parse(parsedB, b);
return std::lexicographical_compare(parsedA, parsedA + 4, parsedB, parsedB + 4);
}
Anything more complicated is going to be harder to maintain and isn't worth your time.
I would create a version class.
Then it is simple to define the comparison operator for the version class.
#include <iostream>
#include <sstream>
#include <vector>
#include <iterator>
class Version
{
// An internal utility structure just used to make the std::copy in the constructor easy to write.
struct VersionDigit
{
int value;
operator int() const {return value;}
};
friend std::istream& operator>>(std::istream& str, Version::VersionDigit& digit);
public:
Version(std::string const& versionStr)
{
// To Make processing easier in VersionDigit prepend a '.'
std::stringstream versionStream(std::string(".") + versionStr);
// Copy all parts of the version number into the version Info vector.
std::copy( std::istream_iterator<VersionDigit>(versionStream),
std::istream_iterator<VersionDigit>(),
std::back_inserter(versionInfo)
);
}
// Test if two version numbers are the same.
bool operator<(Version const& rhs) const
{
return std::lexicographical_compare(versionInfo.begin(), versionInfo.end(), rhs.versionInfo.begin(), rhs.versionInfo.end());
}
private:
std::vector<int> versionInfo;
};
// Read a single digit from the version.
std::istream& operator>>(std::istream& str, Version::VersionDigit& digit)
{
str.get();
str >> digit.value;
return str;
}
int main()
{
Version v1("10.0.0.9");
Version v2("10.0.0.10");
if (v1 < v2)
{
std::cout << "Version 1 Smaller\n";
}
else
{
std::cout << "Fail\n";
}
}
First the test code:
int main()
{
std::cout << ! ( Version("1.2") > Version("1.3") );
std::cout << ( Version("1.2") < Version("1.2.3") );
std::cout << ( Version("1.2") >= Version("1") );
std::cout << ! ( Version("1") <= Version("0.9") );
std::cout << ! ( Version("1.2.3") == Version("1.2.4") );
std::cout << ( Version("1.2.3") == Version("1.2.3") );
}
// output is 111111
Implementation:
#include <string>
#include <iostream>
// Method to compare two version strings
// v1 < v2 -> -1
// v1 == v2 -> 0
// v1 > v2 -> +1
int version_compare(std::string v1, std::string v2)
{
size_t i=0, j=0;
while( i < v1.length() || j < v2.length() )
{
int acc1=0, acc2=0;
while (i < v1.length() && v1[i] != '.') { acc1 = acc1 * 10 + (v1[i] - '0'); i++; }
while (j < v2.length() && v2[j] != '.') { acc2 = acc2 * 10 + (v2[j] - '0'); j++; }
if (acc1 < acc2) return -1;
if (acc1 > acc2) return +1;
++i;
++j;
}
return 0;
}
struct Version
{
std::string version_string;
Version( std::string v ) : version_string(v)
{ }
};
bool operator < (Version u, Version v) { return version_compare(u.version_string, v.version_string) == -1; }
bool operator > (Version u, Version v) { return version_compare(u.version_string, v.version_string) == +1; }
bool operator <= (Version u, Version v) { return version_compare(u.version_string, v.version_string) != +1; }
bool operator >= (Version u, Version v) { return version_compare(u.version_string, v.version_string) != -1; }
bool operator == (Version u, Version v) { return version_compare(u.version_string, v.version_string) == 0; }
https://coliru.stacked-crooked.com/a/7c74ad2cc4dca888
Here's a clean, compact C++20 solution, using the new spaceship operator <=>, and Boost's string split algorithm.
This constructs and holds a version string as a vector of numbers - useful for further processing, or can be disposed of as a temporary. This also handles version strings of different lengths, and accepts multiple separators.
The spaceship operator lets us provide results for <, > and == operators in a single function definition (although the equality has to be separately defined).
#include <compare>
#include <boost/algorithm/string.hpp>
struct version {
std::vector<size_t> data;
version() {};
version(std::string_view from_string) {
/// Construct from a string
std::vector<std::string> data_str;
boost::split(data_str, from_string, boost::is_any_of("._-"), boost::token_compress_on);
for(auto const &it : data_str) {
data.emplace_back(std::stol(it));
}
};
std::strong_ordering operator<=>(version const& rhs) const noexcept {
/// Three-way comparison operator
size_t const fields = std::min(data.size(), rhs.data.size());
// first compare all common fields
for(size_t i = 0; i != fields; ++i) {
if(data[i] == rhs.data[i]) continue;
else if(data[i] < rhs.data[i]) return std::strong_ordering::less;
else return std::strong_ordering::greater;
}
// if we're here, all common fields are equal - check for extra fields
if(data.size() == rhs.data.size()) return std::strong_ordering::equal; // no extra fields, so both versions equal
else if(data.size() > rhs.data.size()) return std::strong_ordering::greater; // lhs has more fields - we assume it to be greater
else return std::strong_ordering::less; // rhs has more fields - we assume it to be greater
}
bool operator==(version const& rhs) const noexcept {
return std::is_eq(*this <=> rhs);
}
};
Example usage:
std::cout << (version{"1.2.3.4"} < version{"1.2.3.5"}) << std::endl; // true
std::cout << (version{"1.2.3.4"} > version{"1.2.3.5"}) << std::endl; // false
std::cout << (version{"1.2.3.4"} == version{"1.2.3.5"}) << std::endl; // false
std::cout << (version{"1.2.3.4"} > version{"1.2.3"}) << std::endl; // true
std::cout << (version{"1.2.3.4"} < version{"1.2.3.4.5"}) << std::endl; // true
int VersionParser(char* version1, char* version2) {
int a1,b1, ret;
int a = strlen(version1);
int b = strlen(version2);
if (b>a) a=b;
for (int i=0;i<a;i++) {
a1 += version1[i];
b1 += version2[i];
}
if (b1>a1) ret = 1 ; // second version is fresher
else if (b1==a1) ret=-1; // versions is equal
else ret = 0; // first version is fresher
return ret;
}