检查C++中stoi()函数的int极限
Checking the int limits in stoi() function in C++
我得到了一个字符串y,其中确保它只由数字组成。在使用stoi函数将其存储在int变量中之前,如何检查它是否超过了整数的界限?
string y = "2323298347293874928374927392374924"
int x = stoi(y); // The program gets aborted when I execute this as it exceeds the bounds
// of int. How do I check the bounds before I store it?
您可以使用异常处理机制:
#include <stdexcept>
std::string y = "2323298347293874928374927392374924"
int x;
try {
x = stoi(y);
}
catch(std::invalid_argument& e){
// if no conversion could be performed
}
catch(std::out_of_range& e){
// if the converted value would fall out of the range of the result type
// or if the underlying function (std::strtol or std::strtoull) sets errno
// to ERANGE.
}
catch(...) {
// everything else
}
stoi函数的详细描述以及如何处理错误
捕获异常:
string y = "2323298347293874928374927392374924"
int x;
try {
x = stoi(y);
}
catch(...) {
// String could not be read properly as an int.
}
如果字符串表示的值太大而无法存储在int
中,则将其转换为更大的值,并检查结果是否适合int
:
long long temp = stoll(y);
if (std::numeric_limits<int>::max() < temp
|| temp < std::numeric_limits<int>::min())
throw my_invalid_input_exception();
int i = temp; // "helpful" compilers will warn here; ignore them.
相关文章:
- 在函数 'int main(int, char**) 中,没有声明 'MIN'
- 错误:无效使用非静态成员函数"int test::hotplug_callback(libusb_contex
- 重载函数 int vs double
- 错误 C2084:函数"int main(void)"已具有主体
- 无效使用非静态成员函数 int test::funcAB(int, int)
- 错误:函数"int open(...)"的隐式声明
- 如何在没有参数的情况下实现返回双向链表大小的函数?int size() const.
- 错误:参数太少,无法函数"int Solution(std::vector<int>, int)"
- arr++ 在函数"int f(int arr[])"中是什么意思?
- 带有声明帐户的C 构造函数(int = 0);
- 如何初始化一个在C++中期望向量和变量的构造函数<int>?
- C++,实现函数"int next(std::string param)"时出现奇怪的编译器错误
- 单链表交换函数(int,int)
- 插入 std::map<int, std::vector 的简短函数<int>>
- 函数int get()和istream&get(char&c)有什么区别
- 该函数 int f() 没有警告不返回任何值?
- 没有用于启动"ostream_iterator"的匹配构造函数<int>
- 函数"int __cdecl invoke_main(void)"中引用LNK2019未解析的外部符号_main错误 (?invoke_main@@YAHXZ)
- 函数"int (*function())[10];"是什么意思?
- 非成员函数 'int find(const T&)' 不能有 cv 限定符