【问题标题】:string with numbers change type to long int带数字的字符串将类型更改为 long int
【发布时间】:2018-04-14 00:28:21
【问题描述】:

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

【问题讨论】:

  • Item_int 到底是什么?
  • 请阅读minimal reproducible example。鉴于您在此处显示的代码,没有人能够确切地告诉您为什么会得到该输出。如果不相关,您可以从示例中删除 Item_int

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


【解决方案1】:

12836564128606764591 的数字大于 long long 的数字。

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

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

    • 正在遍历字符串以查找是否有非数字字符。
    • number = Long.parseLong(stringT); 你确定这是 C++ 吗?
    猜你喜欢
    • 2017-01-04
    • 1970-01-01
    • 2019-04-08
    • 2018-01-04
    • 2017-07-08
    • 1970-01-01
    • 2020-04-18
    • 2015-03-18
    • 1970-01-01
    相关资源
    最近更新 更多