C++ convert string to uint64_t

Try std::stoull if you are using C++11 or greater.

This post may also be of help. I didnt mark this as a duplicate because the other question is about C.


If you're using boost, you could make use of boost::lexical_cast

#include <iostream>
#include <string>
#include <boost-1_61/boost/lexical_cast.hpp> //I've multiple versions of boost installed, so this path may be different for you

int main()
{
    using boost::lexical_cast;
    using namespace std;

    const string s("2424242");
    uint64_t num = lexical_cast<uint64_t>(s);
    cout << num << endl;

    return 0;
}

Live example: http://coliru.stacked-crooked.com/a/c593cee68dba0d72


You can use strtoull() from <cstdlib> if you are using C++11 or newer. Else if you need this with c99 as well, you can go for strtoull() function in stdlib.h from C.

See the following example

#include <iostream>
#include <string>
#include <cstdlib> 

int main()
{
  std::string value= "14443434343434343434";
  uint64_t a;
  char* end;
  a= strtoull( value.c_str(), &end,10 );
  std::cout << "UInt64: " << a << "\n";
}

Try this:

#include <iostream>
#include <sstream>
#include <cstdint>

int main() {
    uint64_t value;
    std::istringstream iss("18446744073709551610");
    iss >> value;
    std::cout << value;
}

See Live Demo


That may work for out of date standards too.

Tags:

C++

String

Uint64