USING A VECTOR TO PRINT OUT A REPEATED WORD

Hey guy i am pretty much a novice in C++ and i have been using Bjarne Stroustrup's Book, Programing Principles in C++ 2nd edition. There was one task where i was asked to create a vector of strings and input the strings using the push_back member function and then define a string called disliked and if that word is typed in it should output bleep alongside the other inputed words but i keep getting nonsensical output as i believe my approach did not address the problem fully.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <cmath>
#include <cstdlib>
#include <cctype>

using namespace std;
inline void keep_window_open() {char ch; cin >> ch;}
int main()
{
    vector<string> Words; string disliked = "Brocolli";
     for(string text; cin >> text;)
        Words.push_back(text);
    cout << "Number of Words: " << Words.size() << '\n';
    for(int i = 0; i < Words.size(); ++i)
        if(i == 0 || Words[i - 1] != Words[i])
            if(Words[i] == disliked)
                cout << "Bleep!!!" << '\n';
}
 i keep getting nonsensical output

if you've shared your entire program then you shouldn't be getting any output at all as your input loop never ends:
1
2
for(string text; cin >> text;)
Words.push_back(text);
> your input loop never ends

The loop will exit on input failure (eof on stdin).

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
#include <iostream>
#include <vector>
#include <string>

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

int main()
{
    vector<string> Words;
    const string disliked = "Brocolli"; // ideally, const

    // end input with eof: ctrl+D (unix/unix-clone) / ctrl+Z (windows)
    for( string text; cin >> text; ) Words.push_back(text);

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

    for( std::size_t i = 0; i < Words.size(); ++i ) // for each word in the vector
    {
        // if there is no earlier word (i==0)
        // or if this word is not identical to the previous word
        if( i == 0 || Words[i-1] != Words[i] )
        {
            // if this word is the disliked word, print "Bleep"
            if( Words[i] == disliked ) cout << "Bleep!!!" << '\n';

            // otherwise print the word
            else cout << Words[i] << '\n' ;
        }
    }
}

http://coliru.stacked-crooked.com/a/edbcf833ea56ac9f
// end input with eof: ctrl+D (unix/unix-clone) / ctrl+Z (windows)
platform dependent, a size limit or a keyword to quit would be more neutral
JLBorges Thank you so much, i guess the part i miss was to nest the if statement which carries the if-else, i ran the code and it did exactly what i wanted it to do, thanks so much for your help, i greatly appreciate and look forward to improving my overall C++ experience.
Topic archived. No new replies allowed.