Skip to content

Instantly share code, notes, and snippets.

@raineorshine
Created March 21, 2013 00:13
Show Gist options
  • Select an option

  • Save raineorshine/5209682 to your computer and use it in GitHub Desktop.

Select an option

Save raineorshine/5209682 to your computer and use it in GitHub Desktop.
How to avoid 'break' in your while loop logic (Beginner)
// A
// [get some input from the user and store it in string str]
bool zFound = false;
while(str != "done")
{
if(str.startsWith("Z"))
{
cout << "Z encountered! Terminating!" << endl;
break;
}
doSomething();
doSomethingElse();
// get next input from user
}
// B: How is this different from example A?
while(str != "done" && !str.startsWith("Z"))
{
doSomething();
doSomethingElse();
// get next input from user
}
// C: Same functionality as A without using a break
while(str != "done" && zFound==false) // what is zFound?
{
doSomething();
doSomethingElse();
if(str.startsWith("Z"))
{ zFound = true;
cout << "Z encountered! Terminating!" << endl;
// change some variable which will trigger the end of the loop
}
// get next input from user
}
if(zFound)
{
count << "Ended with a Z!" << endl;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment