C++ 使用sstream将std::string转换为int
我试图将任意长度的字符串转换为int,但到目前为止,它只适用于长度有限的字符串。迄今为止的代码:C++ 使用sstream将std::string转换为int,c++,string,type-conversion,sstream,C++,String,Type Conversion,Sstream,我试图将任意长度的字符串转换为int,但到目前为止,它只适用于长度有限的字符串。迄今为止的代码: long long convertToInt (std::string x){ long long number; std::istringstream ss(x); ss >> number; return number;} 对于x=1000000000000000001,函数返回0。有人能解释一下原因吗?谢谢 值1000000000000000001太大,无
long long convertToInt (std::string x){
long long number;
std::istringstream ss(x);
ss >> number;
return number;}
对于x=1000000000000000001,函数返回0。有人能解释一下原因吗?谢谢 值1000000000000000001太大,无法放入long-long或无符号long-long,因此提取失败
用于确定实现中类型的最大值:
#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";
1000000000000000001的值太大,无法放入long-long或无符号long-long,因此提取失败
用于确定实现中类型的最大值:
#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";
编译器提供的内置整数类型只能保证能够存储特定大小的数字。看起来你的号码比这个大。您可能会发现C++程序正在报告错误-尝试……/P>
if (ss >> number)
return number;
throw std::runtime_error("conversion of string to int failed");
…或任何其他您喜欢的错误处理
如果您必须使用较大的数字,您可以尝试使用double,或者如果这不适合您的需要,请查看任意精度库,如GMP-您将发现许多关于处理较大数字的stackoverflow问题,并给出相应的答案,对比并说明GMP和备选方案。编译器提供的内置整数类型只能保证能够存储特定数量级的数字。看起来你的号码比这个大。您可能会发现C++程序正在报告错误-尝试……/P>
if (ss >> number)
return number;
throw std::runtime_error("conversion of string to int failed");
…或任何其他您喜欢的错误处理
如果您必须使用较大的数字,您可以尝试使用double,或者如果这不适合您的需要,请查看任意精度库,如GMP-您将发现许多关于处理较大数字的stackoverflow问题,并给出相应的答案,对比并说明GMP和替代品。您希望它返回什么?对于1000000000000000001来说,即使是long-long也太短。您可能需要使用long-long-long-long-long-long-long-long-long-long-long-long-long。您可能需要查看一个库,例如。@retiredInja,但是long-long对于GCC来说太长了。您希望它返回什么?即使long-long对于1000000000000000001来说也太短。您可能需要签出一个库,例如@RetiredInja,但是long对于GCC来说太长了。那么如果我想让函数处理任意长度的字符串,我应该指定什么返回类型呢?@maddy,注释中链接中描述的那个。@maddy,可能有一些大整数库支持您的要求,但我不熟悉它们。@maddy那个更好;那么,如果我想让函数处理任意长度的字符串,我应该指定什么样的返回类型呢?@maddy,注释中链接中描述的返回类型。@maddy,可能有一些大整数库支持您的要求,但我不熟悉它们。@maddy那一个更好;