所以我是新手c ++学习者。我刚刚完成了“使用C ++的原理和实践”(第2版)的前4章。一本书中有一个问题基本上要求我在一个句子中读取而不是过滤它来“ble”我不喜欢的词。所以我的想法是,首先我读到任何我不喜欢看到的向量的单词,然后我在另一个向量中读出一个句子,然后打印出来。然后我尝试将“打印输出”向量中的每个元素与“不喜欢”向量进行比较,如果它们相同,我会将其重写为“嘟嘟”。但我无法弄清楚如何编写代码。谁能帮我?如果我的想法是错的,有没有更简单的方法来做到这一点?谢谢
#define _SILENCE_STDEXT_HASH_DEPRECATION_WARNINGS
#include "../../../std_lib_facilities.h"
int main()
{
vector<string> disliked;
cout << "Enter the disliked words: ";
for (string dword; cin >> dword;)
disliked.push_back(dword);//inserting words to vector that's used to
//compare with
vector<string> words;
cout << "Enter words: \n";
for (string word; cin >> word;)
words.push_back(word);
cout << "Number of words: " << words.size() << '\n';//inserting words to
//vector in order to print out
for (int x = 0, y = 0; x < words.size() , y < disliked.size(); x++, y++)
if (words[x] = disliked[y])//this part is where it says it's wrong
words[x] = "beep";
sort(words.begin(),words.end());
for (int i = 0; i < words.size(); i++)
if (i == 0 || words[i - 1] != words[i])
cout << words[i]<<'\n'; //not show repeated words
答案 0 :(得分:1)
由于for循环中的条件&c;&gt;&gt;&#34;实际上并不足够,它会占用您输入的任何字符或字符串,因此您输入的所有单词都会被推入不喜欢的向量本身。
所以将条件改为类似的,当用户给出字符串时停止for循环&#34; END&#34;什么的。
for (string dword; cin >> dword && dword!="END";)
disliked.push_back(dword);
以下部分代码也是错误的,
for (int x = 0, y = 0; x < words.size() , y < disliked.size(); x++, y++)
{
if (words[x] = disliked[y])//this part is where it says it's wrong
words[x] = "beep";
}
你需要检查每个不喜欢的向量字符串到每个字符串向量。比较应该是这样的。
for (int x = 0; x < words.size() ; x++)
{
for(int y=0;y<disliked.size();y++)
{
if (words[x] == disliked[y])
words[x] = "beep";
}
}