2

I need to convert a (decimal, if it matters) string representation of a number input from a text file to a UINT64 to pass to my data object.

    size_t startpos = num.find_first_not_of(" ");
    size_t endpos = num.find_last_not_of(" ");
    num = num.substr(startpos, endpos-startpos+1);
    UINT64 input;
    //convert num to input required here

Is there any way to convert an std::string to a UINT64 in a similar way to atoi()?

Thanks!

Edit: Working code below.

size_t startpos = num.find_first_not_of(" ");
size_t endpos = num.find_last_not_of(" ");
num = num.substr(startpos, endpos-startpos+1);
UINT64 input; //= std::strtoull(num.cstr(), NULL, 0);

std::istringstream stream (num);
stream >> input;
George G
  • 61
  • 1
  • 8

3 Answers3

4

Use strtoull or _strtoui64(). Example:

std::string s = "1123.45";
__int64 n = std::strtoull(s.c_str(),NULL,0);
  • Thanks! I'm trying to search how I can get the pointers to the beginning and end of the std::string, but havn't found anything yet. Do you know how I can get these? – George G Jul 19 '16 at 12:44
  • @IpqD I have updated the answer. Regarding the string, there are: [string.begin()](http://www.cplusplus.com/reference/string/string/begin/) and [string.end()](http://www.cplusplus.com/reference/string/string/end/) iterators. –  Jul 19 '16 at 12:53
  • Thanks again :). I included the library, but my project seems to say that std has no member "strtoull". Would you know if this is something I have done wrong? Also, is there a difference between __int64 and UINT64? – George G Jul 19 '16 at 13:02
  • 1
    `uint64_t` is the standard fixed length 64 bit unsigned integer type. It is an optional part of the C standard, defined in ``, in C++ therefore in ``. – Jan Henke Jul 19 '16 at 13:17
2

There are at least two ways to do this:

  1. Construct a std::istringstream, and use our old friend, the >> operator.

  2. Just convert it yourself. Parse all the digits, one at a time, converting them to a single integer. This is a very good exercise. And since this is an unsigned value, there isn't even a negative number to worry about. I would think that this would be a standard homework assignment in any introductory computer science class. At least it was, back in my days.

Cody Gray - on strike
  • 239,200
  • 50
  • 490
  • 574
Sam Varshavchik
  • 114,536
  • 5
  • 94
  • 148
0

you can use stoull:

char s[25] = "12345678901234567890"; // or: string s = "12345678901234567890";
uint64_t a = stoull(s);
dima.rus
  • 183
  • 1
  • 8