简体   繁体   中英

How to convert wchar_t* to long c++

As the title indicates I need to know the best way to convert wchar_t* to long in visual c++. Is it possible to do that? If possible how to do that?

Use _wtol() to Convert a wide-character string to a long.

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

Use 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

Use 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 .

Use 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

I ran some benchmarks with 100 samples of each of these methods as well as _wtol converting the string L"123" .

基准

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM