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

时间:2015-08-14 09:30:49

标签: c++ windows winapi visual-c++ wchar-t

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

2 个答案:

答案 0 :(得分:6)

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

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

答案 1 :(得分:4)

使用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"

benchmark