【发布时间】:2020-07-23 20:24:19
【问题描述】:
每当我输入除整数以外的任何内容时,我都希望 catch 块能够执行,但我得到了这个错误:
A03.exe 中 0x002D0C39 处的未处理异常:堆栈 cookie 检测代码检测到基于堆栈的缓冲区溢出。发生了
带我去:
在 A03.exe 中的 0x76D44192 处引发异常:Microsoft C++ 异常:内存位置 0x0116D83C 处的 std::invalid_argument。
A03.exe 中 0x000608B9 处的未处理异常:堆栈 cookie 检测代码检测到基于堆栈的缓冲区溢出。
我已经尝试了各种不同的 catch 块和异常,但都有相同的错误。有人可以告诉我我做错了什么吗?谢谢!
代码如下:
int main() {
while (true) {
std::string input;
int num = 0;
std::cout << "What number do you want to show?";
std::cin >> input;
try
{
num = std::stoi(input);
if (num >= 0 && num < 10)
{
std::cout << "FILLER: This will draw the number";
exit(0);
}
else {
std::cout << "FILLER: This is the else";
exit(1);
}
}
catch (std::runtime_error e)
{
std::cout << e.what();
//std::cout << "That is not a valid number." << '\n';
}
}
return 0;
}
更新:编辑了异常处理程序,但仍然出错:
int main() {
while (true) {
std::string input;
int num = 0;
std::cout << "What number do you want to show?";
std::cin >> input;
try
{
num = std::stoi(input);
if (num >= 0 && num < 10)
{
std::cout << "FILLER: This will draw the number";
exit(0);
}
else {
std::cout << "FILLER: This is the else";
exit(1);
}
}
catch (std::invalid_argument &e)
{
std::cout << e.what();
//std::cout << "That is not a valid number." << '\n';
}
}
return 0;
}
【问题讨论】:
-
Looks good to me。错误必须在其他地方,否则我在添加内容以使其编译时意外修复了问题。我建议创建一个minimal reproducible example。
-
听起来好像
input有问题。 -
我添加了完整的主要功能以便更好地说明。
-
注意:
stoi不会抛出runtime_errors。以前的Looks good to me 的重新剪辑。请添加您用于输入问题的内容,并完成添加您使用的标题。有时它很重要。 -
我尝试输入单个字母“d”、多个字母(如“dd”)和特殊字符(如“!”)。调试中的输出错误:在 A03.exe 中的 0x76D44192 处引发异常:Microsoft C++ 异常:内存位置 0x0116D83C 处的 std::invalid_argument。 A03.exe 中 0x000608B9 处未处理的异常:堆栈 cookie 检测代码检测到基于堆栈的缓冲区溢出。