【发布时间】:2021-11-15 04:29:58
【问题描述】:
我一直在学习 Codecademy 的 C++ 课程,我已经完成了,但我对最后一个任务感到困惑。
我们必须创建一个程序,将所选单词过滤为“脏话”,并用所选字符替换它们。
我在 Visual Studio 中编写了代码,如下所示 main.cpp
#include <iostream>
#include <string>
#include "functions.h"
int main()
{
std::string word = "broccoli";
std::string sentence = "I sometimes eat broccoli.";
bleep(word, sentence);
for (int i = 0; i < sentence.size(); i++) {
std::cout << sentence[i];
}
std::cout << "\n";
}
functions.cpp
#include <iostream>
#include <string>
#include "functions.h"
void asterisk(std::string word, std::string &text, int i) {
for (int k = 0; k < word.size(); k++) {
text[i + k] = '*';
}
}
void bleep(std::string word, std::string &text) {
for (int i = 0; i < text.size(); i++) {
int match = 0;
for (int j = 0; j < word.size(); j++) {
if (text[i + j] == word[j]) {
match++;
}
}
if (match == word.size()) {
asterisk(word, text, i);
}
}
}
函数.h
#pragma once
void bleep(std::string word, std::string &text);
void asterisk(std::string word, std::string &text, int i);
现在,当我在 Visual Studio 中运行此代码时,我得到一个与字符串下标相关的断言,它超出了范围。但是使用相同的代码,它可以在浏览器代码编辑器中的 Codecademys 中运行。 我一生都无法弄清楚为什么它不能在 VS 中运行。
【问题讨论】:
-
可能与问题无关,但是否有任何理由使用循环打印
main中的string而不是更简单的std::cout << sentence; -
Visual Studio 在调试模式下会添加一些 C++ 标准不需要的额外检查,以帮助您发现缓冲区溢出等常见错误。看起来它有助于找到一个。
-
这里有一个错误:
text[i + j]你必须确保 i+j 小于 text.size()
标签: c++ string for-loop replace function-definition