Breaking out of two loops.

Nov 25, 2015 at 3:03pm
Here, if it encounters a bad word, I want it to print [TOS violation] and NOT print the word. How do I do it?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
 //bleeper
#include "std_lib_facilities.h"

int main()
{	vector<string>list;
	vector<string>dislike = {"hate","damn","hell","cheater"};
	for(string temp; cin >> temp;)
		list.push_back(temp);


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

		for(string x : dislike)
			if(list[i] == x)
			 cout << "[TOS Violation]"; 

			cout << list[i];
	}

cout << "\n";
}
Nov 25, 2015 at 4:45pm
Suggestions:
1. use a bool variable, set it to true at line 12. If the list item is found in the dislikes, set the variable to false (and optionally exit the inner loop).
At line 17 test the boolean variable to decide whether to print the word or the error message,

2. use std::find in the <algorithm> header

1
2
3
4
5
6
7
    for (string & item : list)
    {
        if (dislike.end() == find (dislike.begin(), dislike.end(), item))
            cout << item;
        else 
            cout << "[TOS Violation]";
    }


http://www.cplusplus.com/reference/algorithm/find/
Last edited on Nov 25, 2015 at 4:46pm
Nov 26, 2015 at 1:15am
Ah thanks a lot, Chervil!
Topic archived. No new replies allowed.