运行编译的 a.out 后出现分段错误(核心转储)错误
Segmentation fault (core dumped) error after running compiled 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;
}
相关文章:
- 在某些循环内使用vector.push_back时出现分段错误
- 为什么在运行时没有向我们提供有关分段错误的更多信息?
- 如何解决gcc编译器优化导致的centos双编译器设置中的分段错误
- 当我的阵列太大时出现分段错误
- 分段错误当我试图运行程序时出错
- 在c++中初始化矩阵时出现分段错误(核心转储)
- 尝试使用集合函数时出现分段错误
- 我无法缩小此分段错误的原因
- g++的分段错误(在NaN上使用to_string两次时)
- 为什么我使用 std::copy() 收到运行时错误(分段错误)?
- 为什么我的代码包含错误分段错误(核心转储)?
- 为什么会出现此错误?- 分段错误(核心转储)
- 意外的运行时错误(分段错误)
- C++将文本文件读入数组,运行错误:分段错误
- mmap 错误:分段错误/指针无效错误
- 在我的代码中找不到错误....分段错误
- 错误:分段故障(核心转储)阵列
- 用string.h将错误分段到队列中
- c++字符串流转换错误:分段错误
- 为什么我的代码显示错误分段错误(核心转储)