【问题标题】:c++ long long int is not enough?? errorsc++ long long int 还不够??错误
【发布时间】:2011-08-02 10:38:50
【问题描述】:

我正在使用 C++。我有一个包含以下数字的字符串

std::string s= "8133522648";

我想把这个数字转换成

long long int nr;

我做到了:nr=atoll(s.c_str()).result is: -456410944。如何解决这个错误?谢谢

编辑:

其实我有:

const char* str="8133523648";
I have to convert it into long long int nr=8133523648

感谢您的帮助!欣赏!

【问题讨论】:

  • 您的意思是std::string s = "8133522648"; 吗?还有atoll(s.c_str()) ?
  • 另外,nr=atoll(s) 不应该是 nr=atoll(s.c_str()) 吗?
  • 你用的是什么编译器?您能否发布一个可编译的示例?!

标签: c++ int long-integer


【解决方案1】:

使用 int64_t 而不是 long long。在 stdint.h 中定义

如果你依赖 boost 你可以使用

std::string s= "8133522648";
int64_t nr = boost::lexical_cast<int64_t, std::string>(s);

【讨论】:

  • 没有区别 - 所有定义 int64_t 的标准也将 long long 定义为 >= 64 位类型。
  • stdint.h 可能适用于大多数编译器,但不是 C++ 标准。
  • 很高兴知道。我的 c++ 书只是说我应该更好地使用 int64_t、uint32_t...
【解决方案2】:

可以通过以下更好的方式完成:

#include <sstream>

stringstream sstr;
sstr << "8133522648";

long long nr;
sstr >> nr;

不要使用atoll(),因为它不是由 C++ 标准定义的。一些编译器可能会实现它,而其他编译器则不会。还有,

std::string s = 8133522648;

不代表

std::string s = "8133522648";

这可能是你想要的。

【讨论】:

  • atoll 是 C 标准的,所以当他包含 时它会工作..每个编译器都会工作..问题是他有库..
  • @nirmus:问题被标记为 C++,在 C++03 中既没有定义 atoll 也没有定义 long long。但是,您可以假设大多数支持long long 的编译器也支持atoll
  • @mike:我不知道long long 不是由 C++03 定义的。 :(
  • 我在 ubuntu 中工作,我用 g++ 编译。我已经编辑了我的问题。需要帮助
  • @Donotalo:它在 C++11 中,现代编译器目前正在实施。因此,如果它有效,也就不足为奇了。
【解决方案3】:

以下代码运行良好:

    #include <iostream>
    #include <cstdio>
    #include <cstdlib>

    using namespace std;

    int main() {

       std::string s= "8133522648";
       long long int nr = atoll(s.c_str());
       cout << nr;
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-05-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-26
    • 2016-07-29
    • 1970-01-01
    相关资源
    最近更新 更多