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

converting std::string to int using sstream

本文关键字:int 转换 string std 使用 sstream      更新时间:2023-10-16

我试图将任意长度的字符串转换为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和替代品。