c++ - boost 程序选项在从命令行读取时更改数据(这是 boost 中的错误吗?)

标签 c++ boost boost-program-options

我在 boost::program options 中有这段代码:

("output_path,o", po::value< std::string >(&outputPath)->implicit_value(""), "path to where the output should be created.")

在命令行上我有:

-o "C:\My Data\ImagesWithDifferentResolution\"

当boost选项用数据填充outputPath时,我在变量中得到这个值:

 C:\My Data\ImagesWithDifferentResolution"

注意路径末尾的额外引号。

如何修复它?

编辑1

需要明确的是,这是 boost 中的一个错误。我知道在编译代码时应该转义字符串,但这是 boost 程序选项工作并从命令行提取输入数据的方式。

再解释一下:

我的程序名为 testPrg.exe,我尝试通过以下方式调用它:

 testprg.exe -o "C:\My Data\ImagesWithDifferentResolution\"

这是正确的,我的用户应该能够做到这一点。无需在命令行上转义\。

但是boost程序选项,错误地将最后一个\"转换成了转义值。

显示错误的测试应用程序:

main()
{
    po::options_description desc("Allowed options");
    std::string outputPath;
    desc.add_options()
    ("output_path,o", po::value< std::string >(&outputPath)->implicit_value(""), "path to where the output should be created.")
                ;
    po::variables_map vm;
    po::store(po::command_line_parser(argc, argv).options(desc).positional(p).run(), vm);
    po::notify(vm);
    std::cout<<outputPath <<std::endl;
 }

使用 boost 1.58 编译 cod 并按照上面的说明运行它并检查输出。

最佳答案

这不是 Boost.Program_options 中的错误;这是编译器提供的 Microsoft C/C++ 启动代码的预期行为。也就是说,\" 在传递给 argv 中的 main 时已经转换为 " .

来自Parsing C Command-Line Arguments在 Visual Studio 2015 引用中:

A double quotation mark preceded by a backslash, \", is interpreted as a literal double quotation mark (").

Command-Line Input | argv[1] | argv[2] | argv[3]
-------------------+---------+---------+---------
"ab\"c" "\\" d     | ab"c    | \       | d

一个可能的解决方法是调用 GetCommandLine 来获取 lpCommandLinepass that to split_winmain (尽管这可能与 Microsoft 启动代码具有相同的行为)或自行拆分命令行。

关于c++ - boost 程序选项在从命令行读取时更改数据(这是 boost 中的错误吗?),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32381884/

相关文章:

c++ - 列对齐问题

java - 如何设置不按字节边界划分的位值

c++ - 带有 boost boost::program_options 和 options_description 的 RAII

c++ - Boost.Program_options : Forward parameters after '--' to another program

c++ - 为什么我需要 reinterpret_cast 将 Fred ** const 转换为 void ** const?

c++ - 哈夫曼解码函数重复解压一个字符

c++ - 使用 boost mpl 插入器迭代器的意外结果

c++ - C++ Boost中有回收池结构吗?

c++ - 在 Objective C 和 C++ 组合的 xcode 项目中链接 Boost

c++ - 未定义引用 boost::program_options::abstract_variables_map::operator[]