如何在C++中使用整数限制。"-91283472332"的数字超出了 32 位有符号整数的范围



**代码中的一些问题。我必须把字符串转换成整数。但有有限的32位有符号整数。我使用了`stoi((函数,不记得字符串中的空格,但使用大数字是不可能的**我的代码:

#include <iostream>
#include <string>
#include <limits.h>
using namespace std;
int myAtoi(string str)
{
int Res = 0;
for (int i = 0; i < str.size(); i++)
{
if (str[0] >= 'a' && str[0] <= 'z')
{
return 0;
}
}
for (int i = 0; i < str.size(); i++)
{
if (str[i] == ' ')
i++;
// if(str[i]>='0' || str[i]<='9' )
//// if(str[i]==' ')
////    i++;
Res = stoi(str);
cout << "Res:" << Res << endl;
if (Res <= INT_MIN)
{
return INT_MIN;
}
if (Res >= INT_MAX)
{
return INT_MAX;
}
}
cout << "MIN=" << INT_MAX << endl;
cout << "Res=" << Res;
// return Res;
}

获得stoll()的帮助,它将std::string对象转换为long long类型的整数:

void printLongNumber(std::string str) {
auto number = stoll(str);
std::cout << number << std::endl;
}

最新更新