Debug Error -Abort() Has Been Called

2020-06-12 02:39发布

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.

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 ?

标签: c++ abort
3条回答
Explosion°爆炸
2楼-- · 2020-06-12 02:45

It's probably because stoi() have thrown an invalid_argument exception.

查看更多
戒情不戒烟
3楼-- · 2020-06-12 02:57

There are couple of issues:

  1. When you call superLucky from main, s is empty. stoi(s) throws an exception when s is empty.

  2. The check s.size() > 10 is not robust. It is platform dependent. You can use a try/catch block to deal with it instead of hard coding a size.

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);
}
查看更多
来,给爷笑一个
4楼-- · 2020-06-12 03:00

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

查看更多
登录 后发表回答