I'm trying to write a piece of code that "bleeps" out certain words. I've achieved this, but when attempting to stop the window from closing my cin gets ignored. I'm using "Programming: Principles and Practices Using C++" as a guide.
my code:
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <cmath>
using namespace std;
int main()
{
vector <string> words;
vector <string> bad_words = {"bad", "heck"};
cout << "When you are finished entering words press enter then Control Z." << '\n';
for (string single_word; cin >> single_word;) // read white space seperated words
words.push_back(single_word); // puts it in the vector
for (int i = 0; i < words.size(); ++i) {
if (find(bad_words.begin(), bad_words.end(), words[i])
!= bad_words.end()) //reads through the vector searching for word i
cout << "BLEEP!" << '\n';
else {
cout << words[i] << '\n';
}
}
char stop;
cin >> stop;
}
to expand: It doesn't work when executing the program from visual studio or when executing the program by manually clicking on it.
operator>>
ignores leading whitespace, which includes line breaks. So your reading loop won't end until CTRL-Z is typed, and then the subsequent attempt to read a char
at the end of the program won't have anything to read.
You should instead use std::getline()
to read the user's input up to the line break, then you can use a std::istringstream
to read the words from the read input, eg:
#include <iostream>
#include <string>
#include <sstream>
#include <vector>
using namespace std;
int main()
{
vector<string> words;
vector<string> bad_words = {"bad", "heck"};
string line;
cout << "When you are finished entering words press enter then Control Z." << '\n';
getline(cin, line);
istringstream iss(line);
for (string single_word; iss >> single_word;) // read white space seperated words
words.push_back(single_word); // puts it in the vector
for (int i = 0; i < words.size(); ++i)
{
if (find(bad_words.begin(), bad_words.end(), words[i]) != bad_words.end()) //reads through the vector searching for word i
cout << "BLEEP!" << '\n';
else
cout << words[i] << '\n';
}
char stop;
cin >> stop;
return 0;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.