0

I was doing this exercise on writing a program that takes in words and prints the list of words without repetition. However, I am stuck when the question further asked to replace a word of choice(that I dislike) to "Bleep".

Here is the code:

#include <iostream>
#include <vector>
using namespace std;

int main()
{
    vector<string>words;
    string temp;

    while (cin>>temp)
        words.push_back(temp);

    cout << "Number of words: " << words.size() << "\n";

    for (int i = 0; i<words.size(); ++i)
        if(i == 0 || words[i-1] != words[i])
            cout << words[i] << '\n';



    return 0;
}

How can I add codes to change a string input by the user for example 'cute' to 'Bleep'? Thank you so much.

3
  • Just get that input word from the user, and add an if/else inside the while loop... BTW, your question kinda leaves the impression that you're asking us to do your homework for you. Commented Feb 1, 2017 at 6:46
  • you can use std::find if iterator return is not the end then you can use this iterator to change the value. Commented Feb 1, 2017 at 6:48
  • 1
    If you need list of words without repetition, u need to use set<T> instead of vector<T>. Other than that, use answer from @acraig5075 Commented Feb 1, 2017 at 7:05

3 Answers 3

3

You can compare the input word with a list of prohibited words and continue according to whether the input word is in the list or not.

#include <algorithm>

vector<string> badWords = { "bad", "words", "for", "example", "cute" };

while (cin>>temp)
{
  if (std::find(badWords.begin(), badWords.end(), temp) == badWords.end())
    words.push_back(temp);
  else
    words.push_back("bleep");
}
Sign up to request clarification or add additional context in comments.

Comments

1

Just Change your

while (cin>>temp)
    words.push_back(temp);

this block to the following block:

vector<string> bad_words = { "beautiful", "nice", "sweet", "cute" };  // The badwords you have
while (cin>>temp){
    for(int i=0; i<bad_words.size(); i++){
        if(bad_words[i]==temp){
            temp="bleep";
            break;
        }
    }
    words.push_back(temp);
}

Comments

0

Am I right that by

prints the list of words without repetition

you mean transform your initial vector of strings to the vector of unique strings? In such a case your algorithm is wrong. Look at the part

for (int i = 0; i<words.size(); ++i)
    if(i == 0 || words[i-1] != words[i])
        cout << words[i] << '\n';

This algoritm does not handle the cases where two or more repetitions are separated. For example

input: word1 word2 word3 word1 word1 word1
output: word1 word2 word3 word1

The output vector includes two equal words.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.