问:编写一个程序,"ble"你不喜欢的单词; 也就是说,你用cin阅读单词并在cout上再次打印它们.如果一个单词是你定义的几个单词之一,你就会写出BLEEP而不是那个单词.(stroustrup的c ++书)
这是我写的代码:
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <cmath>
using namespace std;
inline void keep_window_open() { char ch; cin >> ch; }
int main()
{
vector<string> disliked;
disliked.push_back("Broccoli");
disliked.push_back("Carrots");
disliked.push_back("Tomatoes");
disliked.push_back("Asparagus");
vector<string> words;
string word;
while (cin >> word) {
words.push_back(word);
}
for (int i = 0; i < words.size(); ++i) {
cout << words[i] << "\t"; //i used it to see if the program was working
}
for (int j = 0; j < disliked.size(); ++j) {
cout << disliked[j] << "\t";
}
for (i = 0; i < j; ++i) {
if (words[i] == disliked[j]) {
cout << "BLEEP";
}
else {
}
}
}
Run Code Online (Sandbox Code Playgroud)
我认为问题是由于我的最终for循环而产生的,但我不明白该做什么.
这是我得到的错误:
bleep.cpp: In function ‘int main()’:
bleep.cpp:27:8: error: name lookup of ‘i’ changed for ISO ‘for’ scoping [-fpermissive]
bleep.cpp:27:8: note: (if you use ‘-fpermissive’ G++ will accept your code)
bleep.cpp:27:19: error: name lookup of ‘j’ changed for ISO ‘for’ scoping [-fpermissive]
Run Code Online (Sandbox Code Playgroud)
Rak*_*kib 10
问题是:
for (i = 0; i < j; ++i) {
if (words[i] == disliked[j]) {
cout << "BLEEP";
}
else {
}
}
Run Code Online (Sandbox Code Playgroud)
在这里,您正在使用i而j不是声明它们.以前的声明只包含您声明的块范围.您必须重新声明它们,或者如果您想使用先前的值,请将它们声明在第一个for循环之上.