3

我有一个简单的代码,可以很好地与输入选项一起使用,它只包含 ASCII 字符,但是会抛出一个异常,错误消息是“错误:字符转换失败”。有解决办法吗?

背景资料:

    1. Compiler and OS: VC++2012 running on Windows 8.1 64 bit    
    2. "_UNICODE" option is ON    It works with command like: tmain.exe --input
    3. "c:\test_path\test_file_name.txt"    It fails with command like:
         tmain.exe --input "c:\test_path\test_file_name_中文.txt"    My default
    4. I am using boost v1.53.
    5. locale is Australian English.

这是源代码:

#include <boost/program_options.hpp>
int _tmain(int argc, _TCHAR* argv[])
{
    try {
        std::locale::global(std::locale(""));
        po::options_description desc("Allowed options");
        desc.add_options()
            ("input",  po::value<std::string>(), "Input file path.")
        ;

        po::variables_map vm;        
        po::store(po::parse_command_line(argc, argv, desc), vm);
        po::notify(vm);    

        if (vm.count("input")) { 
            std::cout << "Input file path: " << vm["input"].as<std::string>();
        }
        return 0;
    }
    catch(std::exception& e) {
        std::cerr << "error: " << e.what() << "\n";
        return 1;
    }
    catch(...) {
        std::cerr << "Exception of unknown type!\n";
    }
    return 0;
}

我已经进入了boost代码,发现这个函数抛出了异常(boost_1_53_0\libs\program_options\src\convert.cpp):

BOOST_PROGRAM_OPTIONS_DECL std::string 
to_8_bit(const std::wstring& s, 
            const std::codecvt<wchar_t, char, std::mbstate_t>& cvt)
{
    return detail::convert<char>(
        s,                 
        boost::bind(&codecvt<wchar_t, char, mbstate_t>::out,
                    &cvt,
                    _1, _2, _3, _4, _5, _6, _7));
}

当我进入boost代码时,我发现这个语句

boost::program_options::parse_command_line(argc, argv, desc)

实际上工作正常,是 boost::program_options::store() 函数无法将 utf-8 中的字符串转换回 wstring。此失败的原因可能是我当前的代码页不支持非 ASCII 字符。如果我当前的语言环境是基于中文的,我想我的代码会很好用。我的问题有什么解决办法吗?提前谢谢了。

4

1 回答 1

0

要使选项能够识别 Unicode,必须使用wvalue而不是添加value. 尝试这个:

desc.add_options()("input",  po::wvalue<std::string>(), "Input file path.");
于 2014-02-25T08:15:50.133 回答