boost::program_options - 解析多个命令行参数,其中一些是包括空格和字符的字符串
我想使用 boost::program_options 解析多个命令行参数。但是,某些参数是用双引号括起来的字符串。这就是我所拥有的 -
void processCommands(int argc, char *argv[]) {
std::vector<std::string> createOptions;
boost::program_options::options_description desc("Allowed options");
desc.add_options()
("create", boost::program_options::value<std::vector<std::string> >(&createOptions)->multitoken(), "create command")
;
boost::program_options::variables_map vm;
boost::program_options::store(boost::program_options::parse_command_line(argc, argv, desc), vm);
boost::program_options::notify(vm);
if(vm.count("create") >= 1) {
std::string val1 = createOptions[0];
std::string val2 = createOptions[1];
...
// call some function passing val1, val2.
}
}
当我这样做时,它工作得很好,
cmdparsing.exe --create arg1 arg2
这样做时,它不起作用
cmdparsing.exe --create "this is arg1" "this is arg2"
但是当我从 Windows 命令行中 。对于第二个选项,它在 createOptions 向量中转换为 ["this" "is" "arg1" "this" "is" "arg2"]
。因此,val1
获取 "this"
并且 val2
获取 “is”
分别代替 “这是 arg1”
和 “这是 arg2”
。
我如何使用 boost::program_option 来完成这项工作?
I want to parse multiple command line arguments using boost::program_options. However, some arguments are strings enclosed in double quotes. This is what I have -
void processCommands(int argc, char *argv[]) {
std::vector<std::string> createOptions;
boost::program_options::options_description desc("Allowed options");
desc.add_options()
("create", boost::program_options::value<std::vector<std::string> >(&createOptions)->multitoken(), "create command")
;
boost::program_options::variables_map vm;
boost::program_options::store(boost::program_options::parse_command_line(argc, argv, desc), vm);
boost::program_options::notify(vm);
if(vm.count("create") >= 1) {
std::string val1 = createOptions[0];
std::string val2 = createOptions[1];
...
// call some function passing val1, val2.
}
}
this works fine when I do
cmdparsing.exe --create arg1 arg2
But does not work when I do
cmdparsing.exe --create "this is arg1" "this is arg2"
from windows command line. For second option, it gets converted to ["this" "is" "arg1" "this" "is" "arg2"]
in createOptions vector. Thus, val1
gets "this"
and val2
gets"is"
instead of "this is arg1"
and "this is arg2"
respectively.
How can I use boost::program_option to make this work ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我使用本机 Windows 函数修复了它,该函数以不同的方式处理命令行参数。有关详细信息,请参阅 CommandLineToArgvW。在将其传递给 processCommands() 之前,我使用上述方法修改 argv[] 和 argc。感谢 Bart van Ingen Schenau 的评论。
I fixed it using a native Windows function which handles command line arguments differently. See CommandLineToArgvW for details. Before passing it to processCommands(), I am modifying my argv[] and argc using the method mentioned above. Thank you Bart van Ingen Schenau for your comment.
您应该能够通过位置选项来实现此目的:
然后在解析命令行时添加以下 pos_desc:
You should be able to achieve this with
positional options
:Then when you parse the command line add this
pos_desc
: