I'm trying to convert 64bit integer string to integer, but I don't know which one to use.
相关问题
- Sorting 3 numbers without branching [closed]
- Multiple sockets for clients to connect to
- How to compile C++ code in GDB?
- Why does const allow implicit conversion of refere
- thread_local variables initialization
You've tagged this question c++, so I'm assuming you might be interested in C++ solutions too. You can do this using
boost::lexical_cast
orstd::istringstream
if boost isn't available to you:Both styles work on Windows and Linux (and others).
In C++11 there's also functions that operate on
std::string
, includingstd::stoull
which you can use:In modern c++ I would use std::stoll.
http://en.cppreference.com/w/cpp/string/basic_string/stol
Use
strtoull
if you have it or_strtoui64()
with visual studio.Something like...
..then just use
atoll()
. You may want to change the#ifdef WINDOWS
to something else, just use something that you can rely on to indicate thatatoll()
is missing butatoi64()
is there (at least for the scenarios you're concerned about).Try
strtoull()
, orstrtoul()
. The former is only in C99 and C++11, but it's usually widely available.When choosing between C-style functions like strtoll (which are of course easy to use with std::string as well) and std::stoll (which at first glance appears better suited for std::string) or boost::lexical_cast: Be aware that the two latter will throw exceptions in case they cannot parse the input string or the range overflows. Sometimes this is useful, sometimes not, depends what you're trying to achive.
If you are not in control of the string to parse (as it's external data) but you want to write robust code (which always should be your desire) you always need to expect corrupted data injected by some malicious attacker or broken outside components. For corrupted data strtoll will not throw but needs more explicit code to detect illegal input data. std::stoll and boost::lexical_cast do auto detect and signal crappy input but you must make sure to catch exceptions somewhere to avoid being terminated(TM).
So choose one or the other depending on the structure of the surrounding code, the needs of the parsed results (sometimes illegal data being "parsed" into a 0 is absolutely OK) the source of the data to parse and last but not least your personal preferences. Neither of the functions available is generally superiour to the others.