I am writing in C++ and I have a string. I want to check if this string is only numbers and If it is I want to change the type to long int.
stringT = "12836564128606764591";
bool temp = false;
for(char& ch : stringT)
{
if(!isdigit(ch))
{
temp=true;
break;
}
}
if(temp != true)
{
itm = new Item_int((long long) strtoll(stringT.c_str(), NULL, 0));
std::cout << " itm:" << *itm << std::endl;
}
but the result of print is: 9223372036854775807
First iterate over a string to find any non-numeric characters
bool is_number(const std::string& s)
{
std::string::const_iterator it = s.begin();
while (it != s.end() && std::isdigit(*it)) ++it;
return !s.empty() && it == s.end();
}
Than convert string to int if is_number is succesful
long int number = 0;
if (is_number(stringT))
{
number = std::stol(stringT);
}
The number 12836564128606764591
is larger than what can fit into a long long
.
The maximum a long long
can hold is 9223372036854775807
(assuming long long
is 64 bits.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.