c++ - C ++ - 程序检查向量中指定的单词
问题描述
我的程序应该将输入的单词与被删减的单词向量进行比较;任何应该被审查的单词都会打印“BLEEP”而不是单词。但是,我遇到的问题是,我的嵌套 for 循环是将输入的单词与向量中的第一个审查单词进行比较,然后显示一些内容,与第二个进行比较,显示等等,而不是将单词与整个向量,然后显示某些内容,然后继续输入下一个单词。我该如何解决这个循环?
int main()
{
vector<string> censored = {"Rabbit", "Food", "Dog", "Monkey", "Zebra", "Kiwi"}; //Censored words
cout << "Please enter words followed by a space. Ctrl+Z when you're done.\n";
vector<string> words;
for (string entry; cin >> entry;) //Reads words separated by a space
words.push_back(entry); //Puts words into vector words
for (int w = 0; w < words.size(); w++) //Checks a word through censored vector before going to next word
for (int c=0; c < censored.size(); c++)
if (words[w] == censored[c])
cout << "\nBLEEP";
else
cout << "\n" << words[w];
keep_window_open();
}
解决方案
您已经找到问题所在,并且可以执行它!
我遇到的问题是我的嵌套 for 循环正在将输入的单词与向量中的第一个审查单词进行比较,然后显示一些东西,与第二个比较,显示等等
正是这个程序,
for (int w = 0; w < words.size(); w++) // For each word
for (int c=0; c < censored.size(); c++) // and each censored word
if (words[w] == censored[c]) // compare them ...
cout << "\nBLEEP";
else
cout << "\n" << words[w];
目的是
在显示某些内容之前将单词与整个向量进行比较,然后继续输入下一个单词
因此代码可能会更改为
for (int w = 0; w < words.size(); w++) // For each word
{
bool in_censored = false; // we will find whether the world is in censored vector.
for (int c=0; c < censored.size(); c++) // For each censored word
if (words[w] == censored[c]) // compare
in_censored = true; // if same, the result for the word is set.
if (in_censored) // If the word is in censored.
cout << "\nBLEEP"; // ...
else
cout << "\n" << words[w];
}
推荐阅读
- javascript - 如何在构造函数和“父对象”中创建一个 JS 对象作为构造函数参数?
- c++ - 变量作为 C++11 属性参数
- flutter - 如何在颤动中为BottomNavigationBar菜单提供onPress功能?
- windows - 如何更改文件夹的用户权限以便 postgres 可以访问它?
- python-3.x - 如何使用 pandas 读取带有特定引用的 csv 文件
- javascript - 如何动态创建点符号对象路径以将数据推送到数组中
- c# - “运行到光标”命令是否可以跳过vs2017中的断点
- scala - 在新消息中使用任何以前的消息
- r - 使用 dplyr 内连接,其中要连接的变量是一个变量
- swift - 打印语句在 iPad Playgrounds 中无法正常工作