Censor words in a string
Sep 30, 2016 at 6:12pm UTC
Hi, I´m trying to make a program that censor a text. The program is suppose to take one integer that says how many words the program needs to censor(fewer than 10 words). Next the program takes in the words that need to be censored and after that the sentence comes.
Then I need to print out the sentence with "*" instead of the censored words.
The input is like: 2 do damn what do I damn need. and the output is then: what ** I *** need.
The code that I have come up whit is :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
#include <iostream>
#include <string>
using namespace std;
int main()
{
int num;
string censor_words;
string sentence;
cin >> num;
getline(cin, censor_words);
//cout << censor_words << endl;
getline (cin, sentence);
//cout << sentence <<endl;
int counter = 0;
unsigned int pos = sentence.find(censor_words);
if (pos < sentence.length()) {
counter ++;
while (sentence.find(censor_words, pos+1) < sentence.length() ) {
counter++;
//pos = sentence.find(censor_words, pos+1);
}
int number = 10;
for (int i=0; i < number ; i++) {
cout << censor_words[i];
}
counter ++;
}
return 0;
}
I´m not sure why I´m doing here and I can´t figure out how to print the words that I´m trying to censor
Sep 30, 2016 at 7:34pm UTC
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
#include <iostream>
#include <string>
#include <set>
#include <sstream>
using namespace std;
int main()
{ int num;
std::set<string> censor;
string sentence;
string temp;
string word;
cout << "Enter <num> <censored words> <sentence>" << endl;
cin >> num;
// Build the list of censored words
for (int i=0; i<num; i++)
{ cin >> temp;
censor.insert (temp);
}
getline (cin, sentence);
stringstream ss(sentence);
while (ss >> word)
{ if (censor.find (word) == censor.end())
{ // word not found in censored list
cout << word << " " ;
}
else
{ // word found in censored list
cout << "*** " ;
}
}
cout << endl;
system ("pause" );
return 0;
}
Enter <num> <censored words> <sentence>
2 do damn what do I damn need.
what *** I *** need.
Press any key to continue . . .
Last edited on Sep 30, 2016 at 7:35pm UTC
Sep 30, 2016 at 9:10pm UTC
Thank you! what can I use instead of std::set<string> and stringstream ?
(#include <set>
#include <sstream>)
Oct 1, 2016 at 12:04am UTC
Lado wrote:
what can I use instead of std::set<string> and stringstream ?
Perhaps, a vector instead of a set. As for stringstream, maybe a loop.
Topic archived. No new replies allowed.