gpt4 book ai didi

c++ - echo在Boost中输入命令行参数

转载 作者:行者123 更新时间:2023-11-30 01:58:11 25 4
gpt4 key购买 nike

我正在使用 boost::program_options解析命令行参数。我希望我的程序将输入的参数回显给用户进行验证。这听起来像是一项简单的任务,但我无法找到一个优雅的解决方案。

问题在于用户可以输入各种数据类型(字符串、整数、 bool 值等)。通常这可以通过 boost 很好地处理。但是我无法将这些值转换回字符串以便将它们回显给用户。

这是我目前正在做的事情

// set up program options
po::options_description optdesc("Allowed options");
optdesc.add_options()
("help", "Produces this help screen")
("opt1", po::value<string>(), "Option 1")
("opt2", po::value<int>(), "Option 2")
("opt3", po::value<bool>(), "Option 3);

// parse command line
try
{
po::store(po::parse_command_line(argc, argv, optdesc), cmdline);
po::notify(cmdline);
}

// do error handling ...

// echo parameters back to user
for (po::variables_map::iterator it = cmdline.begin(); it != cmdline.end(); ++it)
{
boost::any arg = it->second.value();
if (typeid(string) == arg.type())
{
cout << " " << it->first << ": " << boost::any_cast<string>(it->second.value()) << endl;
}
else if (typeid(int) == arg.type())
{
cout << " " << it->first << ": " << boost::any_cast<int>(it->second.value()) << endl;
}
// etc...

我真的不喜欢这个解决方案。由于 Boost 能够将用户输入从字符串转换为适当的值,因此它也应该能够将值转换回字符串表示形式,而无需我明确测试数据类型。

这可能吗?如果是,我该怎么做。

谢谢

最佳答案

你已经有了argvargc,只需将它们回显给用户

#include <iostream>
#include <iterator>

int
main(int argc, char* argv[])
{
std::cout << "got " << argc << " args" << std::endl;
std::copy(argv + 1, argv + argc, std::ostream_iterator<char*>(std::cout, " "));
std::cout << std::endl;
}

产生

samm:stackoverflow samm$ ./a.out asdf 1 2 3 hello world
got 7 args
asdf 1 2 3 hello world
samm:stackoverflow samm$

无需遍历 variables_map 并转换每个条目。

关于c++ - echo在Boost中输入命令行参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17784516/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com