Convert an ASCII string to long long
I've got some line开发者_StackOverflow社区s of information from a data-file in C++. One information is a 12 character long number. How can I convert this from string to long long (I think long long is most suitable for this) without data loss?
In C++, there is no long long
data type. It's available in C99. However, you can use int64_t
. Include <stdint.h>
.
Use boost::lexical_cast
to convert string into int64_t
.
Or you can write a convert function yourself as:
int64_t convert(const std::string &s)
{
if(s.size() == 0 )
std::runtime_error error("invalid argument");
int64_t v = 0;
size_t i=0;
char sign = (s[0] == '-' || s[0] == '+') ? (++i, s[0]) : '+';
for( ; i < s.size(); ++i)
{
if ( s[i] < '0' || s[i] > '9' )
throw std::runtime_error("invalid argument");
v = v * 10 + s[i] - '0';
}
return sign == '-' ? -v : v;
}
Test code:
int main() {
try{
std::cout << convert("68768768") << std::endl;
std::cout << convert("+68768768") << std::endl;
std::cout << convert("-68768768") << std::endl;
std::cout << convert("68768768x") << std::endl;
}catch(const std::exception &e)
{
std::cout << e.what() << std::endl;
}
return 0;
}
Output:
68768768
68768768
-68768768
invalid argument
Online demo : http://ideone.com/nnSLp
A 64-bit bit integer is enough to represent any 12-digit decimal number (with plenty of room to spare). Thus, depending on your platform, it could be that a long
will suffice. If that's the case, you could use strtol
or strtoul
.
If you do find that you need a long long
, take a look at strtoll
and strtoull
.
精彩评论