Break In A Loop
/* * This is another approach to the important cheese problem. */ #include <iostream> #include <string> using namespace std; int main() { while(true) { // Request the user to say cheese, and read the response. cout << "Please say \"cheese\": "; string input; std::getline(std::cin, input); // If complied, done. if(input == "cheese") break; // Issue corrective message. cout << "You have not complied with our instructions." << endl; } cout << "Thank you for your cooperation." << endl; }

The break statement can also be used to immediately end a loop. It is generally used inside an if as shown here to essentially add a loop test in the middle of the body. Whether is is better to complicate the body with a conditional break, rather than complicate the loop test, often with an additional flag, is a point of debate.

[more info]