带数字的字符串将类型更改为long int

时间:2017-11-01 16:09:14

标签: c++ string types long-integer strtol

我用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

2 个答案:

答案 0 :(得分:0)

首先遍历字符串以查找任何非数字字符

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);
}

答案 1 :(得分:0)

12836564128606764591的数量大于long long的数量。

long long可容纳的最大值为9223372036854775807(假设long long为64位。

相关问题