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_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::program_options::parse_command_line(argc, argv, desc)

実際には正常に動作します。utf-8 の文字列を wstring に戻すのに失敗するのは boost::program_options::store() 関数です。この失敗の理由は、現在のコード ページが非 ASCII 文字をサポートしていない可能性があります。現在のロケールが中国語ベースのロケールであれば、私のコードはうまく機能すると思います。私の問題の解決策はありますか?よろしくお願いします。

4

1 に答える 1