提问者:小点点

C++中来自中止(3)(SIGABRT)的中止信号


#include <iostream>
using namespace std;

int main()
{
    //code
    int test;
    cin >> test;
    while(test--)
    {
        int count = 0;
        string input;
        cin >> input;
        for (int j = 0; j < input.length() - 2; j++)
        {
           if (input.substr(j, 3) == "gfg")
           {
                count +=1;
           }
        }
        if (count > 0)
        {
            cout << count << endl;
        }
        else
        {
            cout << -1 << endl;
        }
        
    }
    return 0;
}

这段代码显示中止信号从中止(3)(SIGABRT),同时提交在极客为极客,而运行在本地计算机上完美,甚至在各种在线编译器上完美。 想不出这个问题。 有人能帮忙吗?


共2个答案

匿名用户

想一想当input少于两个字符时会发生什么。

input.length()是一个无符号的量,因此input.length()-2会绕到一个天文数字。

j是一个天文数字时,input.substr(j,3)效果不好:它抛出异常std::OUT_OF_RANGE; 由于没有捕捉到此异常,程序将终止。

这些竞赛测试是否覆盖了所有可能的输入域,特别是边缘情况。 在编写算法时一定要考虑到它们。

匿名用户

我认为。substr需要字符串库。 出于某种原因,你不需要它在本地。

尝试添加

#include <string>

编辑:我尝试了一些变体

if(input.length()<2)
{
cout<<-1<<"\n" ;
break;
}

for循环应该帮助(input.length()在减去比它的值更多的值时不会溢出。

相关问题


MySQL Query : SELECT * FROM v9_ask_question WHERE 1=1 AND question regexp '(c++|中|中止|sigabrt|中止|信号)' ORDER BY qid DESC LIMIT 20
MySQL Error : Got error 'repetition-operator operand invalid' from regexp
MySQL Errno : 1139
Message : Got error 'repetition-operator operand invalid' from regexp
Need Help?