Simple Vector Problem

I made a program that BLEEPS disliked words. The output of this vector seems to read the sentence one word at a time and after each word it starts at the first word again. Ex. (reads the first word, then reads the first word again, then the second, and then starts at the beginning again till the third word, etc). Is there a way to get it to just output the entire sentence without repeating itself?

Here is my code

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
//vector: disliked words
#include<iostream>
#include<string>
#include<vector>
#include<algorithm>
#include<cmath>
using namespace std;
inline void keep_window_open(){char ch; cin>>ch;}
int main() //execute main
{
    vector<string>sent; //create string vector
    string word=""; //declare string word
    string bleep="BLEEP"; //declare string bleep
    while (cin>>word){ //read string word
        sent.push_back(word); //put word input into vector sent

        cout<<"Number of words: "<<sent.size()<<endl;

     for (int i=0; i<sent.size(); ++i){
            if (sent[i]!="broccoli") //if word is string disliked present output
                cout<<sent[i]<<'\n';
        else
            cout<<bleep<<'\n';
        }
    }
    keep_window_open();
        return 0;
}


Here is the output for "Name is broccoli"

Number of words: 1
Name
Number of words: 2
Name is
Number of words: 3
Name is BLEEP

Is there a way to just have the final Number of words: 3 'Name is BLEEP' output?
Look at the structure of your loops.

Your for loop at line 19 is within the scope of your while loop, so you're going to execute the for loop for each iteration of the while loop.

What you want is to have only line 15 within the scope of the while loop. That way you build the entire vector of words first. Then after you've completed the while loop, enter your for loop to display the words.
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
#include<iostream>
#include<string>
#include<vector>
#include<algorithm>
#include<cmath>

using namespace std;

inline void keep_window_open(){ char ch; cin >> ch; }

int main() { //execute main

    vector<string> sent; //create string vector
    string word ; /* = "" */ ; //declare string word
    const string bleep = "BLEEP"; //declare string bleep

    while (cin >> word){ //read string word
        sent.push_back(word); //put word input into vector sent
    } // *** end while ***

    cout << "Number of words: " << sent.size() << '\n' ; // endl;

    for (int i=0; i<sent.size(); ++i){

        if (sent[i] != "broccoli") //if word is string disliked present output
            cout << sent[i] << '\n';

        else
            cout << bleep << '\n';
    }

    keep_window_open();
    // return 0;
}
Thank you for your help everyone, you were right, it was looping through each iteration.
Topic archived. No new replies allowed.