2014-02-20 67 views
2

我有一个简单的代码,可以很好地处理输入选项只包含ASCII字符,但会抛出一个错误消息为“error:character conversion failed” 。有解决方案吗?boost :: program_option :: store当选项字符串包含混合语言字符时,会抛出异常

背景信息:

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_1_53_0 \库\抛出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)); 
} 

当我进入升压代码时,我发现ou牛逼这种说法

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

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

回答

1

对于一个选项是Unicode知道它必须与wvalue,而不是value添加。试试这个:

desc.add_options()("input", po::wvalue<std::string>(), "Input file path."); 
+0

怎么样的时候,我运行除了程序名不带参数的程序,它抛出'字符转换failed' – Victor

相关问题