在 C++ 中检查 stoi() 函数中的 int 限制

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18534036/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 22:00:02  来源:igfitidea点击:

Checking the int limits in stoi() function in C++

c++stringintbounds

提问by Manmeet Saluja

I have been given a string y in which I'm ensured that it only consists digits. How do I check if it exceeds the bounds of an integer before storing it in an int variable using the stoi function?

我得到了一个字符串 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?

回答by 4pie0

you can use exception handling mechanism:

您可以使用异常处理机制:

#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
}

detailed description of stoi function and how to handle errors

stoi 函数的详细描述以及如何处理错误

回答by Sani Singh Huttunen

Catch the exception:

捕捉异常:

string y = "2323298347293874928374927392374924"
int x;

try {
  x = stoi(y);
}
catch(...) {
  // String could not be read properly as an int.
}

回答by Pete Becker

If there is a legitimate possibility that the string represents a value that's too large to store in an int, convert it to something larger and check whether the result fits in 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.