使用sstream将std::string转换为int型
converting std::string to int using sstream
我试图将任意长度的字符串转换为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 << "100000000000000000000000001n";
打印:<>之前184467440737095516159223372036854775807100000000000000000000000001之前
检查提取尝试的结果以确保提取发生:
if (ss >> number)
{
return number;
}
// Report failure.
编译器提供的内置整数类型只保证能够存储特定幅度的数字。看起来你的数字比这个大。你可能会发现c++程序正在报告错误- try…
if (ss >> number)
return number;
throw std::runtime_error("conversion of string to int failed");
…或者其他你想要的错误处理。
如果你必须使用更大的数字,你可以尝试double
,或者如果它不适合你的需要,那么检查像GMP这样的"任意精度"库-你会发现很多关于处理大数的stackoverflow问题,答案建议,对比和说明GMP和替代品。
相关文章:
- 是否可以从int转换为enum类类型
- 如何在C++中将一个无符号的 int 转换为两个无符号的短裤?
- 是什么导致了这种使用三进制而不是短整型的有符号int到无符号int转换
- 将字符串中的 int 转换为字母;
- 主.cpp:18:20:错误:从"int*"转换为"int"会失去精度 [-fa
- 将非常大的 int 转换为双倍,在某些计算机上会损失精度
- 如何将矢量<int>转换为字符数组?
- C++ 无法从 const int* 转换为 const_iterator
- 我不断收到错误 C2440'=':无法从"int *(__cdecl *)(int *,int *,int,int)"转换为"int *
- 如何将 int[4] 转换为 std::array<int,4>?
- 如何将data[i].int转换为vaible
- 将 int 转换为字符串,然后连接另一个变量以创建完整扩展名,然后将其转换为 const_char*
- 将私有矩阵形式 int 转换为双 C++
- 无法将参数 1 从 'int' 转换为 'int &'
- 将 int 转换为字符串后始终得到 0
- isspace 函数的性能警告,从 int 转换为布尔值
- 将大 int 转换为浮点数,而不舍入 c++
- 错误:无法将'uint8* {aka unsigned int*}'转换为"常量emxArray_uint8_T*"?
- 将未签名的INT转换为BCD
- 在 C++ 中将 int 转换为双精度