[英]string with numbers change type to long int
我正在用 C++ 编写,我有一个字符串。 我想检查这个字符串是否只是数字,如果是,我想将类型更改为 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;
}
但打印的结果是:9223372036854775807
首先遍历字符串以查找任何非数字字符
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();
}
如果 is_number 成功,则将字符串转换为 int
long int number = 0;
if (is_number(stringT))
{
number = std::stol(stringT);
}
数字12836564128606764591
大于long long
所能容纳的数字。
long long
最多可容纳9223372036854775807
(假设long long
为 64 位。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.