由于c++ bool函数的StackOverflowException导致进程终止

process is terminated due to StackOverflowException from bool function C++

本文关键字:进程 终止 StackOverflowException c++ bool 函数 由于      更新时间:2023-10-16

我试图使一个bool函数,将允许字符串的输入和子字符串的输入被搜索在该字符串的输入。bool函数应该递归地搜索匹配项,如果字符串中存在匹配项,则返回true。例如:'word'作为字符串输入,然后'or'是我在字符串中寻找的子字符串。函数应该返回true,因为'or'在'word'内。当我运行代码时,在命令行上它会说,"进程因StackOverFlowException而终止",我对这个错误的含义以及它与我的代码的关系感到困惑。

#include <iostream>
#include <string>
using namespace std;
bool find(string s, string t)
{
if(s.length() <= 1){
    return false;
}
int t_len = t.length() - 1;
string se = s.substr(0, t_len);
if(se == t){
    return true;
}
else
s.erase(0,0);
return find(s, t);
}
int main()
{
string s;
string t;
cout << "Enter string s: " << endl;
cin >> s;
cout << "Enter string t: " << endl;
cin >> t;
bool is_found = find(s, t);
if(is_found = true)
{
    cout << "Found: " << t << " in " << s << endl;
}
system("pause");
return 0;
 }

你对erase的调用没有删除任何字符。erase的定义为:

erase( size_type index = 0, size_type count = npos );

所以您要擦除1字符,而不是0字符。

另外,你的测试在最后应该是:

if(is_found == true)

,否则,您将尝试为is_found赋值true并测试该值(在这种情况下,该值始终为true)。

另外,你还有:

string se = s.substr(0, t_len);

其中t_len不正确(关闭一个),因此字符串比较将不起作用。

基本上,看起来您没有理解erasesubstr的定义,这对于使此正常工作至关重要。