如何将 wchar_t* 转换为 long C++

How to convert wchar_t* to long c++

如标题所示,我需要知道在 Visual C++ 中将 wchar_t* 转换为 long 的最佳方法。有可能这样做吗?如果可能,该怎么做?

使用 _wtol() 将宽字符串转换为长字符串。

wchar_t *str = L"123";
long lng = _wtol(str);

使用boost::lexical_cast.

#include <iostream>
#include <boost/lexical_cast.hpp>

int main()
{
    const wchar_t* s1 = L"124";
    long num = boost::lexical_cast<long>(s1);
    std::cout << num;
    try
    {
        const wchar_t* s2 = L"not a number";
        long num2 = boost::lexical_cast<long>(s2);
        std::cout << num2 << "\n";
    }
    catch (const boost::bad_lexical_cast& e)
    {
        std::cout << e.what();
    }
}

Live demo

使用std::stol.

#include <iostream>
#include <string>

int main()
{
    const wchar_t* s1 = L"45";
    const wchar_t* s2 = L"not a long";

    long long1 = std::stol(s1);
    std::cout << long1 << "\n";
    try
    {
        long long2 = std::stol(s2);
        std::cout << long2;
    }
    catch(const std::invalid_argument& e)
    {
        std::cout << e.what();
    }    
}

Live Demo.

使用std::wcstol

#include <iostream>
#include <cwchar>

int main()
{
    const wchar_t* s1  = L"123";
    wchar_t *end;
    long long1 = std::wcstol(s1, &end, 10);
    if (s1 != end && errno != ERANGE)
    {
        std::cout << long1;
    }
    else
    {
        std::cout << "Error";
    }
    const wchar_t* s2  = L"not a number";
    long long2 = std::wcstol(s2, &end, 10);
    if (s2 != end && errno != ERANGE)
    {
        std::cout << long2;
    }
    else
    {
        std::cout << "Error";
    }
}

Live Demo

我 运行 一些基准测试,每种方法都有 100 个样本,以及 _wtol 转换字符串 L"123".