【发布时间】:2020-06-27 12:21:54
【问题描述】:
#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) 的 Abort 信号,同时在 Geeks for Geeks 中提交,同时在本地计算机上完美运行,甚至在各种在线编译器上完美运行。无法弄清楚问题所在。有人可以帮忙吗?
【问题讨论】:
-
离题但
if(count>0)和if(count)是一样的。 -
@VinaySomawat 我不敢苟同。如果
count增加了足够多的次数以致其容量溢出怎么办?作为有符号整数,它将变成负数。所以,不,它是不一样的,因为它不太可能发生。 -
@SirDarius 是的,你是对的!
-
@SirDarius 至少在 c++17 之前,
int溢出不保证会变成负数。它只是UB,所以检查是等价的。 -
@cigien 够公平!值得一提的是,整数溢出是一个非常重要的错误来源,不容忽视。