vendredi 7 février 2014

char ** conversion to string

First, I would say it was a long time without posting anything, but I’m a bit in trouble in my personal life. And finally today as I was working on a command line implementation I realize that it’s a good practice to log (wherever you want …) the command line argument used to run a command line executable.

And as I was writing the code to do that, I was thinking that some developer may have create some complex code with loop display the command line argument that we have in argv. But in fact if you can use C++ STL and also the powerful BOOST Framework, it use only 2 lines of code (or even less).

So let start, first cmd line arguments are from the main function point of view an array of char*. So the 1st thing to do convert that in the C++ world.

vector<string> cmdline(argv+1, argv+argc);

Ok now we have STL object we all know on which we can easily iterate to concatenate each string and insert a delimiter (a simple space “ ”). But instead of using a complex loop I prefer using an efficient BOOST string algorithm call join.

#include "boost/algorithm/string.hpp"

….

string cl = boost::algorithm::join(cmdline, " ")

now you can dump the argument passed to your command line with a cout or any logging system you want.

And have a nice weekend.

Aucun commentaire :

Enregistrer un commentaire