我正在尝试将任意长度的字符串转换为 int,但到目前为止它仅适用于有限长度的字符串。到目前为止的代码:
long long convertToInt (std::string x){
long long number;
std::istringstream ss(x);
ss >> number;
return number;}
对于 x=100000000000000000000000001
,该函数返回 0
。有人可以解释为什么吗?谢谢。
最佳答案
"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
Check the result of the extraction attempt to ensure extraction occurred:
if (ss >> number)
{
return number;
}
// Report failure.
关于c++ - 使用 sstream 将 std::string 转换为 int,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16434726/