开发者

Using vectors to bleep some predefined strings

So i'm currently doing the exercices in my programming book "Programming: Principles and practice using c++" from Bjarne Stroustrup and i'm curently stuck at one exercice. Basically, the exercice is to write a program that bleeps out words it doesn't like. The way it works is that the user inputs a string and the program repeats the word. If the word the user enters is part of the dislike vector, the word is replaced by "Bleep". (I don't know if I explained this right, but it shouldn't be to complicated to understand).

This is my version of the program:

int main()
{
    string dislike = "Potato";
    string words = " ";

    cout << "Please enter some words: " << endl;
    while(cin>>words)
    {
        if(words==dislike)
        {
            cout << "Bleep!" << endl;
        }

        else
        {
            cout << words << endl;
        }
    }
    system("pause");
    return 0;
}

As you can see, this version isn't using vectors (and it should, because the exercice is right after the explanation of vectors in the chapter). So my question is, how can I implement a vector with many "dislike" words in it like this:

vector<string>dislike;
dislike.push_back("Potatoes");
dislike.push_back("Peanuts");
dislike.push_back("Coconut");

and make it so it works like my other version without vectors (repeats words, but bleeps the dislike words). I can't seem to understand how to navigate in a vector so that it only bleeps the "dislike" words.

If someone could give me a hand and explain to me how it works (please do not just give me the answ开发者_如何学Goer) it would be very appreciated.

Thank you for your time and help, learning c++ alone isn't always simple, and I thank this website for making my learning curve a bit easier.

bobicool


Ok, let me explain a simple approach to it. There are more elegant ones, but for now it's important that you get a feeling of how std::vector can be accessed and how to compose control structures correctly.

Step 1 - looping through all elements of a vector

You can use iterators to go through all elements of a vector.

for(vector<string>::const_iterator it = dislike.begin(); it != dislike.end(); ++it) {

   // now *it gives access to the current element (here: current dislike word)
   if (*it == words) {
       // ... yeah, we found out the current word is on the list!
   }         
}

You get an iterator to the first element in a vector by calling begin(), then keep incrementing (++it) it until you reached the end of the vector. I use const_iterator here because I'm not going to modify any elements, if you need to, use iterator.

with a std::vector, indexing via [index] is also possible (but not recommended, usually):

for(size_t i = 0;i < dislike.size(); ++i) {
   // dislike[i] is the current element

   if (dislike[i] == words) {
      // huuuuray! another BEEEP candidate
   }
}

Step 2 - break the loop early

As soon as you know what for sure that we have a dislike word, you don't need to search the vector further.

for(vector<string>::const_iterator it = dislike.begin(); it != dislike.end(); ++it) {   
  if (*it == words) {
     // we found a positive match, so beep and get out of here
     cout << "Bleep!" << endl;
     break;
  }         
}

Step 3 - make a note if we handled a word already

bool is_beep = false;
for(vector<string>::const_iterator it = dislike.begin(); it != dislike.end(); ++it) {   
  if (*it == words) {
     // we found a positive match, so beep and get out of here
     cout << "Bleep!" << endl;
     is_beep = true;
     break;
  }         
}
// this is not a dislike word if is_beep is false, so print it as usual
if (!is_beep) {
   cout << words << endl;
}

Step 4 - putting it all together

int main()
{
    vector<string>dislike;
    dislike.push_back("Potatoes");
    dislike.push_back("Peanuts");
    dislike.push_back("Coconut");
    string words = " ";

    cout << "Please enter some words: " << endl;
    while(cin>>words)
    {
        bool is_beep = false;
        for(vector<string>::const_iterator it = dislike.begin(); it != dislike.end(); ++it) {   
           if (*it == words) {
            // we found a positive match, so beep and get out of here
            cout << "Bleep!" << endl;
            is_beep = true;
            break;
          }         
        }
       // this is not a dislike word if is_beep is false, so print it as usual
       if (!is_beep) {
            cout << words << endl;
       }
    }
    system("pause");
    return 0;
}

Check out std::find for a more idiomatic solution - it basically saves you the inner loop. You can also get rid of that bool in the last code sample if you re-structure a bit. I'll leave that as an exercise to you (hint: keep the iterator alive and check out its value after terminating the loop).


int main()
{
    vector<string> dislike;
    dislike.push_back("Potatoes");
    dislike.push_back("Peanuts");
    dislike.push_back("Coconut");
    string words;

    cout << "Please enter some words: " << endl;
    while(cin >> words)
    {
        if(find(dislike.begin(), dislike.end(), words) != dislike.end())
        {
            cout << "Bleep!" << endl;
        }

        else
        {
            cout << words << endl;
        }
    }
    system("pause");
    return 0;
}

For std::find add #include <algorithm> to your source.


use std::find(your_vector.begin(), your_vector.end(), words)

int main()
{
    vector<string>dislike;
    dislike.push_back("Potatoes");
    dislike.push_back("Peanuts");
    dislike.push_back("Coconut");
    string words = " ";

    cout << "Please enter some words: " << endl;
    while(cin>>words)
    {
        if(std::find(dislike.begin(), dislike.end(), words) != dislike.end())
        {
            cout << "Bleep!" << endl;
        }

        else
        {
            cout << words << endl;
        }
    }
    system("pause");
    return 0;
}


Here is my solution to that particular question in the book when i was reading it. :) hope it's self-explanatory.

/*THE QUESTION GOES LIKE;
Write a program that “bleeps” out words that you don’t like; that is, you read in words    
using cin and print them again on cout. If a word is among a few you have defined, you
write out BLEEP instead of that word. Start with one “disliked word” such as string
disliked = “Broccoli”; 
When that works, add a few more.*/



#include "std_lib_facilities.h"  // this is a standard library header that came with 
the book

int main () {
vector<string> dislike = {"Dislike", "Alike", "Hello", "Water"};   /* defining a vector  
for the disliked words. */

vector<string> words;  //initializing vector for the read words.

cout << "Please enter some words\n";   //prompt user to enter some words.

for( string word; cin >> word;)  //this current word typed is read in.

    words.push_back(word);   // word read in are pushed into the vector "words".

sort(words);  /* function for the standard library for sorting data...this makes the data from the vector "words" appears in alphabetical order. */

for (int i=0; i<words.size(); ++i){   /*this acts as an iterator. and goes through all the element of the vector "words".  */

    if(i==0 || words[i-1]!=words[i]){   /*this prevents the words from repeating....just an option incase the user enters same kinda words twice or more. */

        if(words[i]!=dislike[0] && words[i]!=dislike[1] && words[i]!=dislike[2] && words[i]!=dislike[3])  /*This test checks whether the words typed match any of the elements of the vector "dislike".if they don't match;   */

            cout << words[i]<< '\n';  //prints out the words.
        else
            cout << "BlEEP!\n";   //if they match....print out "BlEEP!".
       }
   }


}


I am learning C++. This Program has been changed some. Write a program that "bleeps" out bad words that you don't like; that is, you read in words using cin and print them again on cout. If a word is among a few you have defined, you write out BLEEP and or have it to BLEEP(Sound) instead of that word. Start with one "bad word" such as -- string badword = "arse"; When that works, add a few more or write a whole program based on all the bad words that you do not want printed out.

while (cin >> words)
{
    if(find(badwords.begin(), badwords.end(),words) !=badwords.end())
    {
        cout << "      " << endl; // You can put Bleep in or leave it out (Blank) if blank
                                  // it will leave a blank in the phrase when it prints
        Beep(523,500);            // This is to Bleep (Sound) when a bad word is found
        cin.get();                
    }
    else
    {
        cout << words << endl;
    }
}

Since someone gave the answer I have Changed the program some. That is for you to learn. This runs on Visual Studio Express 2012


I have solved this problem using the ideas that have already been learned in the previous chapters, not going beyond what you understand.

#include <iostream>
#include <vector>

using namespace std;

int main()
{ 

vector<string> disliked;

//adding disliked words to the vector

disliked.push_back("dog");
disliked.push_back("cat");
disliked.push_back("goat");
disliked.push_back("cow");
disliked.push_back("sheep");
disliked.push_back("pig");


string words=""; //this variable will store the input from the user.

while(cin>>words)
    {//test every entered word to see if it's equal to any word listed in   disliked words.
        if(words==disliked[0] ||//or
           words==disliked[1] ||//or
           words==disliked[2] ||//or
           words==disliked[3] ||//or
           words==disliked[4] ||//or
           words==disliked[5]){
                               cout<<"Bleeps";}
        else{
             cout<<words;}
}
return 0;
//Not that I have not gone beyond what has been covered in the previous chapters.
//I know their are beautiful solutions to this problem. 
//Keep learning you will know everything.

}


This question was asked a long, long time ago so the author is probably professional at this point lol, but here is simpler yet working solution for anybody who is looking for the same answer. I am learning from the beginning through Bjarne book so im not yet "affected" with higher knowledge to confuse you with but with solutions that are good enough to work based on how far we are in the book. :)

// program that bleeps out words we dont like

vector <string> words;
vector <string> bwords = {"this", "that", "then"}; //bleeped words
string sword; // temporary word

cout << "Enter few words: ";
for (string tword; cin >> tword;)  // read in words
    words.push_back(tword);

//check if they match beeped words

cout << "\n\nWords:\n";
for (int i = 0; i < words.size(); i++)    //take word[i] from the vector
{  
    sword = words[i];    // temporary variable is now word[i]
    for (int j = 0; j < bwords.size(); j++)   // take beeped word[j] from saved words
    {
            if (words[i] == bwords[j]) // is word[i] same as bleeped word[j]
            sword = "BLEEP";  // if word[i] is same then replace sword with BEEP
    }

    cout << sword << "\n"; // now we checked first word and if it matches with any of the bleeped words then it will cout bleep, otherwise it will cout first word.
}

Now in this example you can add many new bleeped words and you wont need to change the code. This is not the best solution in "real life" programming, but at this point in the book we learned for, if, vector(not a lot of it), cout, cin.. etc so anything else just looks confusing..until this point we dont know yet about using :: , begin, true/fals, cin.get or anything like that.


//Josef.L
//2019/7/11

int main(void){
    vector <string> inpute;
    for(string pat; cin >>pat;){
        inpute.push_back(pat);
    }
    for(int i=0; i < inpute.size(); i++){
        if("work"== inpute[i]){
            cout<<"bleep! "<<endl;}
        else if("life" == inpute[i]){
            cout<<"bleep! "<<endl;
        }
        else if("broccoli" == inpute[i]){
            cout<<"bleep! "<<endl;
        }
        else if("homework" == inpute[i]){
            cout<<"bleep! "<<endl;
        }
        else{
            cout <<inpute[i]<<endl;
        }

    }
return 0;}
//However, the entire source code is too long and boring, so there should be an improvement.


That's my solution, where you can add as many words as you want without changing the code.

#include "std_lib_facilities.h"


int main()
{
    vector<string> dislike;
    dislike.push_back("Potatoes");
    dislike.push_back("Peanuts");
    dislike.push_back("Coconut");

    vector<string> words;

    for (string temp_word; cin >> temp_word; )
    {
        for (int i = 0; i < dislike.size(); ++i)
        {
            if (temp_word == dislike[i])
            {
                words.push_back("BLEEP");
                break;
            }
            else if (i == dislike.size() - 1 && temp_word != dislike[dislike.size() - 1])
            {
                words.push_back(temp_word);
                break;
            }
        }
    }

    for (string temp_word : words)
    {
        cout << temp_word << ' ';
    }
    
    keep_window_open();
}


“Simple can be harder than complex: You have to work hard to get your thinking clean to make it simple. But it’s worth it in the end because once you get there, you can move mountains.” ― Steve Jobs

#include "std_lib_facilities.h"

int main()
{
    

    vector<string>disliked;

    disliked.push_back("Apple"); 
    disliked.push_back("OliveOil");
    disliked.push_back("Strawberry");
    disliked.push_back("Lemon");
    
    cout<<"Please type some words:"<<"\n";
    string words=" ";
    while(cin>>words)
    
    {
        if (words==disliked[0] | words==disliked[1]|
            words==disliked[2] | words==disliked[3])
            
        {cout<<"BLEEP"<<"\n";}
    
      else{cout<<words<<"\n";}
    }

    keep_window_open();
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜