开发者

Convert std::string to MSVC specific __int64

May I know ho开发者_运维问答w I can convert std::string, to MSVC specific __int64?


_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): Why doesn't C++ reimplement C standard functions with C++ elements/style?


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;

}


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜