【问题标题】:Cross platform _wtoi() implementation?跨平台 _wtoi() 实现?
【发布时间】:2011-05-26 22:12:44
【问题描述】:

大家好,我正在编写一个软件,由于我选择使用 Qt,我需要重写几百行代码以符合 unicode(qt 强制我的整个项目 _UNICODE)。在写完所有这些代码并让它工作之后,我遇到了 _wtoi() 的问题——它不是跨平台的!

谁能帮助我快速实施?我听说过使用 stringstreams 来做到这一点并保持跨平台,但我以前从未使用过它们,并且将它用作 unicode atoi() 似乎暗示了我。我更希望有人向我解释它,而不是从现成的网站和论坛中复制带有字符串流示例的代码。

谢谢!!

【问题讨论】:

  • 我听说它不像其他解决方案那样安全。不过我可能是错的。
  • 你是。它实际上可以让您检查是否存在一个数字,_wtoi() 只返回 0。

标签: c++ visual-c++ unicode cross-platform g++


【解决方案1】:

试试这个:

inline int wtoi(const wchar_t *str)
{
  return (int)wcstol(str, 0, 10);
}

【讨论】:

    【解决方案2】:

    如果你想要纯粹的 runtime 速度,我推荐Boost.Spirit.Qi:

    #include <cwchar>
    #include <boost/spirit/include/qi_int.hpp>
    #include <boost/spirit/include/qi_parse.hpp>
    
    int portable_wtoi(wchar_t const* const str)
    {
        using boost::spirit::int_;
        using boost::spirit::qi::parse;
    
        wchar_t const* p = str;
        int i;
        return parse(p, str + std::wcslen(str), int_, i) && p != str ? i : 0;
    }
    

    但请注意,您可能会注意到编译时间增加(建议使用预编译头文件)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-29
      • 2018-06-24
      • 1970-01-01
      • 2013-06-23
      • 1970-01-01
      • 1970-01-01
      • 2021-03-15
      • 1970-01-01
      相关资源
      最近更新 更多