运行编译的 a.out 后出现分段错误(核心转储)错误



我正在编写的代码应该将文本中选择的单词替换为"*"。不知道这是工作,但是当我运行编译文件a.out时,出现分段错误错误。有什么帮助吗?

哔.cpp

#include <iostream>
#include <string>
#include "functions.hpp"
int main()  {
std::string word = "broccoli";
std::string text = "I sometimes eat broccoli. There are three interesting things about broccoli. Number One. Nobody knows how to spell it. Number Two. No matter how long you boil it, it's always cold by the time it reaches your plate. Number Three. It's green. #broccoli";

looking_for(text, word);

}

Functions.hpp

#include <string>
#include <vector>

void looking_for(std::string &text, std::string word);

函数.cpp

#include <iostream>
#include <string>
#include <vector>
#include "functions.hpp"
void looking_for(std::string &text, std::string word)
{
for (int i = 0; i < text.size(); i++)
{
int m = i; // saving "i" value when it's equal to b 
std::string tmp;
int j = 0;
if (text[i] == word[j])
{
while (text[i] == word[j] && j < word.size())
{
tmp.push_back(word[j]);
i++;
j++;
}

}
if (tmp == word)
{
for (m; m < m + word.size(); m++)
{
text[m] = '*';
}
}

}
}

希望这有帮助:在 i 的条件和位置中也检查 i,就像在您的情况下一样,它一直在递增,因为您使用相同的 i 向前移动。

#include<bits/stdc++.h>
using namespace std;

void looking_for(string &text, string word)
{
for (int i = 0; i < text.length();i++)
{
int m = i; // saving "i" value when it's equal to b 
int pos = i;
string tmp;
int j = 0;
if (text[i] == word[j])
{
while (i<text.length() && j<word.length() && text[i] == word[j] )
//     ^^^^^^^^^^^^^^^^^^
// i and j tested for validity before being used
{
tmp.push_back(word[j]);
i++;
j++;
}
}
if (tmp.compare(word)==0)
{
// in your case m is getting incremented and m is added up with word.length() which is the result for segmentation fault
for (m=pos; m < pos + word.length(); m++)
{
text[m] = '*';
}
i = i+word.length()-1;
//^^^^^^^^^^^^^^^^^^    // set i to the end of the word as that much is already checked
}
else{
i = m; 
//^^^^     // set it to the stored value as it has to start from the very next character for matching
}
// now i++ will automatically move i forward
}
}
int main(){
string word = "broccoli";
string text = "I sometimes eat broccoli. There are three interesting things about broccoli. Number One. Nobody knows how to spell it. Number Two. No matter how long you boil it, it's always cold by the time it reaches your plate. Number Three. It's green. #broccoli";
looking_for(text, word);
cout<<text<<endl;
}

最新更新