真正的长整数字符串到int转换

时间:2016-08-09 19:09:22

标签: c++ c++builder

我从Google Drive API获取此值作为驱动器大小。

16106127360

如何在c ++ Builder中将该字符串转换为int / long / unsigned。

  1. StrToInt()不能,它表示无效的整数。
  2. atol()也失败,它返回乱码值
  3. 环礁()?我似乎无法在c ++ Builder
  4. 中使用该功能

    C ++构建器的数值数据类型可以保存值16106127360吗?

    感谢

2 个答案:

答案 0 :(得分:4)

16106127360太大,无法容纳32位(unsignedint 1 。该值需要64位(unsigned__int64或(unsignedlong long

有很多不同的方法可以将这样的字符串值转换为64位整数变量:

  • StrToInt64()标题中的StrToInt64Def()值有TryStrToInt64()__int64SysUtils.hpp个函数:

    __int64 size = StrToInt64("16106127360");
    

    __int64 size = StrToInt64Def("16106127360", -1);
    

    __int64 size;
    if (TryStrToInt64("16106127360", size)) ...
    

    (在现代C ++ Builder版本中,UInt64值也有相应的unsigned __int64函数)

  • strtoll()标题中有wcstoll() / stdlib.h个函数:

    long long size = strtoll("16106127360");
    

    long long size = wcstoll(L"16106127360");
    
  • sscanf标题中有stdio.h个函数。使用%lld%llu格式说明符:

    long long size;
    sscanf("16106127360", "%lld", &size);
    

    unsigned long long size;
    sscanf("16106127360", "%llu", &size);
    

    long long size;
    swscanf(L"16106127360", L"%lld", &size);
    

    unsigned long long size;
    swscanf(L"16106127360", L"%llu", &size);
    
  • 您可以在std::istringstream标题中使用std::wistringstreamsstream

    std::istringstream iis("16106127360");
    __int64 size; // or unsigned
    iis >> size;
    

    std::wistringstream iis(L"16106127360");
    __int64 size; // or unsigned
    iis >> size;
    

1 :(如果您正在为iOS 9编译C ++ Builder项目,long为64位,否则在其他所有支持的平台上为32位)

答案 1 :(得分:3)

请参阅this runnable program

此代码使用stringstream应该可以工作:

#include <sstream>
#include <iostream>
#include <string>

int main()
{
    std::string ss = "16106127360";
    std::stringstream in;
    in << ss;
    long long num;
    in >> num;
}