C++ 调试错误 -Abort() 已被调用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24855515/
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
Debug Error -Abort() Has Been Called
提问by MNada
I'm trying to enter a number,n and get the least super lucky number that is more than or equal to n. Super lucky: it's decimal representation contains equal amount of digits 4 and 7. For example, numbers 47, 7744, 474477 are super lucky and 4, 744, 467 are not.
我正在尝试输入一个数字,n 并获得大于或等于 n 的最少超级幸运数字。超级幸运:它的十进制表示包含等量的数字 4 和 7。例如,数字 47、7744、474477 是超级幸运,而 4、744、467 则不是。
Here's my code
这是我的代码
#include<iostream>
#include<string>
using namespace std;
void superLucky(int n,string s, int count4, int count7)
{
if (s.size() > 10)
return;
if (( stoi(s) >= n ) && (count4 == count7) && (count4+count7)!=0)
{
cout << s << endl;
return;
}
superLucky(n, s + '4', count4+1, count7);
superLucky(n, s + '7',count4,count7+1);
}
int main()
{
int n;
cin >> n;
superLucky(n, "", 0, 0);
return 0;
}
Once I input some integer I get debug error R6010 - abort() has been called. What this means ? and how can I fix this ?
一旦我输入了一些整数,我就会收到调试错误 R6010 - abort() 已被调用。这是什么意思?我该如何解决这个问题?
采纳答案by R Sahu
There are couple of issues:
有几个问题:
When you call
superLucky
frommain
,s
is empty.stoi(s)
throws an exception whens
is empty.The check
s.size() > 10
is not robust. It is platform dependent. You can use atry/catch
block to deal with it instead of hard coding a size.
当您调用
superLucky
from 时main
,s
是空的。为空stoi(s)
时抛出异常s
。该检查
s.size() > 10
不可靠。它依赖于平台。您可以使用try/catch
块来处理它而不是硬编码大小。
Here's a more robust version of the function.
这是该函数的更强大版本。
void superLucky(int n,string s, int count4, int count7)
{
int d = 0;
if ( s.size() > 0 )
{
try
{
d = stoi(s);
}
catch (...)
{
return;
}
if (( d >= n ) && (count4 == count7) && (count4+count7)!=0)
{
cout << s << endl;
return;
}
}
superLucky(n, s + '7',count4,count7+1);
superLucky(n, s + '4', count4+1, count7);
}
回答by Yifu Wang
It's probably because stoi()
have thrown an invalid_argument
exception.
可能是因为stoi()
抛出了invalid_argument
异常。
回答by Igor Tandetnik
On the first call to superLucky
, you pass an empty string to std::stoi
. When unable to perform the conversion, stoi
throws an exception. That exception is not caught, so uncaught_exception
gets called, which in turn calls abort
在第一次调用 时superLucky
,您将一个空字符串传递给std::stoi
。当无法执行转换时,stoi
抛出异常。那个异常没有被捕获,所以uncaught_exception
被调用,然后调用abort