使用sstream将std :: string转换为int

时间:2013-05-08 07:11:12

标签: c++ string type-conversion sstream

我正在尝试将任意长度的字符串转换为int,但到目前为止它仅适用于有限长度的字符串。代码到目前为止:

long long convertToInt (std::string x){
   long long number;
   std::istringstream ss(x);
   ss >> number;
   return number;}

对于x=100000000000000000000000001,函数返回0。有人能解释为什么吗?谢谢。

2 个答案:

答案 0 :(得分:5)

"100000000000000000000000001"大到适合long long(或unsigned long long),因此提取失败。

使用numeric_limits确定实施中类型的最大值:

#include <limits>

std::cout << std::numeric_limits<unsigned long long>::max() << "\n";
std::cout << std::numeric_limits<long long>::max() << "\n";
std::cout << "100000000000000000000000001\n";

打印:

18446744073709551615
9223372036854775807
100000000000000000000000001

检查提取尝试的结果以确保提取:

if (ss >> number)
{
    return number;
}
// Report failure.

答案 1 :(得分:1)

您的编译器提供的内置整数类型仅保证能够存储特定大小的数字。看起来你的号码比那个大。您可能会发现C ++程序报告错误 - 尝试...

if (ss >> number)
    return number;
throw std::runtime_error("conversion of string to int failed");

...或者您想要的任何其他错误处理。

如果你必须使用更大的数字,你可以尝试double,或者如果这不符合你的需要,那么看看像GMP这样的“任意精度”库 - 你会发现很多关于处理大量的stackoverflow问题数字与答案暗示,对比和说明GMP和替代品。