tags:

views:

308

answers:

3

May I know how I can convert std::string, to MSVC specific __int64?

+2  A: 

Here's one way:

#include <iostream>
#include <string>
#include <sstream>

using namespace std;

int main() {
    string s( "1234567890987654321");

    stringstream strm( s);

    __int64 x;

    strm >> x;

    cout << x;

}
Michael Burr
+3  A: 

_atoi64, _atoi64_l, _wtoi64, _wtoi64_l

std::string str = "1234";
__int64 v =_atoi64(str.c_str());

See also this link (although it is for linux/unix): http://stackoverflow.com/questions/1771117/why-doesnt-c-reimplement-c-standard-functions-with-c-elements-style/1771471#1771471

skwllsp
A: 

__int64, while an extension, is still just a numeric type. Use whichever method you would typically use.

Boost lexical cast is my favorite. It pretty much wraps up Michaels answer in an easy to use form:

__int64 x = boost::lexical_cast<__int64>("3473472936");

If you can't use boost, you can still do a pretty good job of making a simple version. Here's an implementation I wrote for another answer:

template <typename R>
const R lexical_cast(const std::string& s)
{
    std::stringstream ss(s);

    R result;
    if ((ss >> result).fail() || !(ss >> std::ws).eof())
    {
        throw std::bad_cast();
    }

    return result;
}

It does some extras, like checking for trailing characters. ("123125asd" would fail). If the cast cannot be made, bad_cast is thrown. (Similar to boost.)

Also, if you have access to boost, you can avoid the need to use the MSVC-specific __int64 extension with:

#include <boost/cstdint.hpp>
typedef boost::int64_t int64;

To get int64 on any platform that provides it, without changing your code.

GMan