user5226747
user5226747

Reputation: 33

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?

Upvotes: 2

Views: 2207

Answers (2)

sjdowling
sjdowling

Reputation: 3020

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

benchmark

Upvotes: 4

Deadlock
Deadlock

Reputation: 4519

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

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

Upvotes: 6

Related Questions