将用户输入与矢量中存储的值进行比较



这是我迄今为止的程序。它进行编译,但在最后一部分被卡住并崩溃。我想重复用户的字符串输入,并将字符串中发现的任何坏单词替换为"***"。我的错误很可能是在find_Poop_inSentence中。"调试断言失败。矢量下标超出范围">

void find_Poop_inSentence(vector<string> & v1, vector<string> & v2, string sub);
int main()
{
cout << "Howdy partner, tell me some words you don't take kindly to.n";
vector<string>bad_words;
string word;
while (cin >> word)
{
cin.ignore();
bad_words.push_back(word);
if (word == "exit")
break;
}
cout << "Ok partner, got it!n";
cout << "Now say something and I'll repeat it back to you. Don't worry, I'll bleep out the words that you don't like.n";
word = "";
vector<string> random_sentence; 
while (cin >> word)
{
cin.ignore();
random_sentence.push_back(word);
if (cin.get() == 'n')
break;
}
find_Poop_inSentence(bad_words, random_sentence, "****");
cout << "You said: ";
for (unsigned int i = 0; i < random_sentence.size(); ++i) {
cout << ' ' << random_sentence[i];
}
system("Pause");
return 0;
}
void find_Poop_inSentence(vector<string> & v1, vector<string> & v2, string sub) {
int iterOne;
int iterTwo = 0;
int iteratorMax = v2.size();

for (iterOne = 0; iterOne < iteratorMax; iterTwo++) {
if (v1[iterOne] == v2[iterTwo]) {
v2[iterTwo] == sub;
}
if (iterTwo == iteratorMax ) {
iterOne++;
iterTwo = 0;
}
}
}

您要做的工作不仅仅是带问号的部分。即使您设法实现了替换部件,您的代码仍然无法工作。

find(bad_words.begin(), bad_words.end(), say_back) != bad_words.end())

find()搜索由前两个参数(迭代器的起始值和结束值)给出的序列。这些是您的bad_wordsfind()检查第三个参数给定的值是否首次出现,并返回引用第一个找到的值的迭代器,如果未找到该值,则返回end()

因此,如果bad_words包含"Fudge",并且您在say_back中键入"Fudge",find()就会找到它。

然而,如果你在say_back中输入"肯定是福吉",find()当然找不到。因为你的bad_words中没有一个包含"绝对的福吉"。find()搜索完全匹配。

因此,如果您希望"替换在"say_back字符串中发现的任何坏单词,这将不起作用。

在您开始考虑替换say_back中的任何bad_words之前,您需要找出正确的算法。你需要在say_back中找到每个单独的单词,然后在bad_words中检查每个单独的词。

在你能够正确地实现搜索算法之前,从某种意义上说,弄清楚如何替换你在bad_words中找到的东西就是本末倒置。

你需要先弄清楚这一点;如果需要,你可以随时和你的橡皮鸭交谈。

多亏了我的朋友伊万·德拉戈,我才得以解决这个问题。

void find_Poop_inSentence(vector<string> & v1, vector<string> & v2, string sub);
int main()
{
cout << "Howdy partner, tell me some words you don't take kindly to.n";
vector<string>bad_words;
string word;
while (cin >> word)
{
//cin.ignore();
bad_words.push_back(word);
if (word == "exit")
break;
}
cout << "Ok partner, got it!n";
cout << "Now say something and I'll repeat it back to you. Don't worry, I'll bleep out the words that you don't like.n";
cout << "Push enter twice when done.n";
word = "";
vector<string> random_sentence;
while (cin >> word)
{
//cin.ignore();
random_sentence.push_back(word);
if (cin.get() == 'n')
break;
}
find_Poop_inSentence(bad_words, random_sentence, "****");
cout << "You said: ";
for (unsigned int i = 0; i < random_sentence.size(); ++i) {
cout << ' ' << random_sentence[i];
}
system("Pause");
return 0;
}
void find_Poop_inSentence(vector<string> & v1, vector<string> & v2, string sub) {
for (unsigned int i = 0; i < v1.size(); i++) {
for (unsigned int j = 0; j < v2.size(); j++) {
if (v1[i] == v2[j]) {
v2[j] = sub;
}
}
}
}

相关内容

  • 没有找到相关文章