#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;
}这段代码显示了abort(3) (SIGABRT)中的中止信号,同时在Geek for Geek中提交,而在本地计算机上运行良好,甚至在各种在线编译器上也能完美工作。找不到问题所在。有人能帮帮忙吗?
发布于 2020-06-27 20:40:57
想想当input少于两个字符时会发生什么。
input.length()是一个无符号量,因此input.length() - 2会绕到一个天文数字。
当j是一个天文数字:it throws the exception std::out_of_range时,input.substr(j, 3)就不好用了;因为您没有捕捉到这个异常,所以您的程序将终止。
这些竞赛测试您是否涵盖了所有可能的输入域,特别是边缘情况。在编写算法时,一定要考虑到它们。
发布于 2020-06-27 20:26:05
我认为.substr需要string lib。出于某些原因,您在本地不需要它。
尝试添加
#include <string>编辑:我尝试了一些变体
if(input.length()<2)
{
cout<<-1<<"\n" ;
break;
}之前的for循环应该会有所帮助(input.length()不会在减法超过它的值时溢出。
https://stackoverflow.com/questions/62609948
复制相似问题