weixin_39622399
2020-11-29 07:53 阅读 1

Throw exception "std::range_error" when using nana::menubar::push_back() to push a chinese string

void make_menu() { menu_bar.push_back("&Data Import"); menu_bar.push_back("&Extrume"); menu_bar.push_back("分析"); menu_bar.push_back("&Help"); }

after running "menu_bar.push_back("分析"); " , the program stopped and throw an exception "std::range_error". It looks like that "wide_string from_bytes(const char _First, const char _Last)" has got an error after calling "_Pcvt->in()" .

Thanks for your help. Any suggestion will be very appreciated.

该提问来源于开源项目:cnjinhao/nana

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享

5条回答 默认 最新

  • weixin_39622399 weixin_39622399 2020-11-29 07:53

    The program running on windows10 X64 chinese version and complied by Visual Studio 2013

    点赞 评论 复制链接分享
  • weixin_39949954 weixin_39949954 2020-11-29 07:53

    It's an expected behavior that throws an std::range_error. The parameter whose type is std::string for most API only accepts a string in UTF-8 encoded. So use one of following proper way.

    c++
    menu_bar.push_back(::nana::charset("分析").to_bytes(::nana::unicode::utf8));
    menu_bar.push_back(nana::to_utf8(L"分析")); //VS2013, don't forget L
    menu_bar.push_back(u8"分析"); //other C++11 compilers. e.g VS2015
    

    The prototypes of to_utf8 are

    c++
    const std::string& to_utf8(const std::string& u8text); //directly returns u8text, it must be a UTF-8 string.
    std::string to_utf8(const std::wstring& wtext); //returns a string of wtext in UTF8 encoded.
    

    "分析" is not a UTF-8 string in Windows, so L is required to call the const-ref std::wstring overloading of to_utf8.

    点赞 评论 复制链接分享
  • weixin_39851977 weixin_39851977 2020-11-29 07:53

    Maybe this compile option /utf-8 can be used. https://msdn.microsoft.com/ja-jp/library/mt708821.aspx

    点赞 评论 复制链接分享
  • weixin_39622399 weixin_39622399 2020-11-29 07:53

    Many thanks for your quick responses. I did it as JinHao's advise, it works. Now my project can be moved on. Thanks for beru's advise about the complie option, it provides me another knowledge point. Unfortunately, the option /utf-8 doesn't work on vs2013, maybe it is for vs2015.

    点赞 评论 复制链接分享
  • weixin_39851977 weixin_39851977 2020-11-29 07:53

    You are correct. I hope you'll be able to migrate to newer versions of Visual Studio in future. https://blogs.msdn.microsoft.com/vcblog/2016/02/22/new-options-for-managing-character-sets-in-the-microsoft-cc-compiler/

    点赞 评论 复制链接分享

相关推荐