I have a while loop and I want to skip the whole loop without running the condition in parantheses again becuse as you now, the vector's Size is one greater then their cell number. I mean it is like:
[ Cell 0 ][ Cell 1 ][ Cell 2] --> Size = 3
So I have to skip the whole loop to prevent an Error. I need to write something that takes the program from point A to B without running "while()" My loop:
size = 0;
while ((usernamelog[size] != usrlog || passwordlog[size] != passlog) && size < usernamelog.size())//Checking Username And Password
{
if (x == 2)//Login Unsuccessfull
cout << "Username or Password is Incorrect. Please try again." << endl;
cout << "Enter Your Username: ";
cin >> usrlog;
cout << "Enter Your Password: ";
cin >> passlog;
x = 2;
size++;
if (usernamelog.size() == size)
//Point A
}
//Point B
for example, when usernamelog.size is 2 and size is 2, Jump From A to B
You are looking for break :
After this statement the control is transferred to the statement immediately following the enclosing loop or switch. As with any block exit, all automatic storage objects declared in enclosing compound statement or in the condition of a loop/switch are destroyed, in reverse order of construction, before the execution of the first line following the enclosing loop.
Example:
while (true) {
std::cout << "this loop runs only once";
break;
}
There is an "issue" that comes up sometimes when you have nested loops, so I'll also add it here even not relevant for your code at the moment. Note that break only breaks out of the most inner loop. Once you have more loops you need more than a single break. For example this will run till infinity:
while (true) {
while (true) {
break;
}
}
An easy solution is to put the loops inside a function and to return:
void foo() {
while (true) {
while (true) {
std::cout << "this will be printed only once";
return;
}
}
}
Note that you can do this also for a single loop and often that is the cleaner way.
PS: If you do know the number of iterations beforehand, then it is more idomatic to use a for loop instead. Also consider to fix your conditions such that you do not need to break out of the loop from within the body.
Related
void getPlayerRolls(int RollValues[], int& AttemptCount) {
int i = 0;
int FrameNumber = 0;
int RollNumber = 0;
while(RollValues[i] != -1) {
FrameNumber++;
cout << "Frame # " << FrameNumber << endl;
cout << "Roll #1 "
<< " ";
cin >> RollValues[i];
i++;
cout << "Roll #2 "
<< " ";
cin >> RollValues[i];
i++;
cout << endl;
}
}
My expectation is that when a -1 is entered for one of the roll values that the program terminates. I tried to create a while loop that works with an array but I am having trouble determining how to do this.
I removed lines from your function that are not part of the problem, but maybe this will clarify:
while(RollValues[i] != -1) {
cin >> RollValues[i];
i++;
cin >> RollValues[i];
i++;
i++;
}
What is the value of i by the time the loop condition variable is tested?
The first rollvalue entered is read into some place in the array, but then i is incremented, so if you read back from RollValues[i] you read from a different place in memory! Not only that, you never look at the first roll before accepting the second. And then you increment i yet again. By the time you're back at the top of the loop, i has been advanced 3 times, and neither of the entered rolls is ever tested.
You have other issues too, such as
receiving an array has no "size" information associated, so you do not now how big of an array the caller provided. Your code therefore cannot protect against overruning the memory.
in your while loop, you advance 3 times per iteration, so even if your loop condition checks for boundary cases, you still could have walked off the end of the array before getting back to the top of the loop.
Therefore, I suggest the following:
1) pass in the size of your array into your function, or use a safer data structure, such as std::array or std::vector
2) only process a single roll per loop, and check that you're within bounds before advancing.
3) don't advance your index variable until you're done looking at the value in that place that it refers.
I just completed a program that has to quit when a negative value is entered as input. Everything is working good except for only one issue, it quits the program after the second time a negative value is entered. After some research I noticed the use of break, however the samples I have to guide the assignment use only if and else statement.
#include <iostream>
using namespace std;
int main()
// insert code here...
// create a variable named "pounds" that can be used to store an integer.
// wait for the user to type in a value and put that value into the variable ounces
{
int poundsTotal;
int ouncesTotal;
while (poundsTotal >= 0)
{
cout << "Enter pounds or a negative number to quit: ";
cin >> poundsTotal;
ouncesTotal = poundsTotal * 16;
cout << poundsTotal << " pouds is " << ouncesTotal << " ounces." <<endl;
cout << " Enter pounds or a negative number to quit ";
cin >> poundsTotal;
poundsTotal++;
}
if (poundsTotal == 0){
cout <<"you enter a zero value" <<"Try onemore time";
}
else {
cout << "you chose to quit the program" <<poundsTotal;
}
}
The condition of a while loop is evaluated after the body has been executed. Then it is determined whether the body will be run again. Change your code and add an if statement inside the loop.
if(poundsTotal < 0) break;
And yes, a break statement is useful in a loop. Otherwise you can't stop the loop before your test condition is evaluated to false.
In your case, I find using a break would be a simple option.
When the program first reaches while (poundsTotal >= 0), poundsTotal has no defined value. This puts you at the mercy of the gods as to whether the program will work as expected or not, and Gods are notoriously unreliable. For more information, look up the term Undefined Behaviour.
The solution to this is ask the user for poundsTotal before the loop and once more at the end of the loop.
If you want to get really posh and do this without repeating code (and stay DRY) , make a function that gets poundsTotal from the user and call this function in the while loop's condition. For example,
while ((poundsTotal = getPoundsTotal()) >= 0)
{
...
}
I have a loop that looks something like this
int temp = 0;
int menuItem;
while (temp != -1 && temp < 5)
{
cout << "Order " << temp + 1 << ": ";
cin >> menuItem;
arrayData[temp] = menuItem;
temp++;
break;
}
When I learned to use sentinels, I did not learn them using break...
for example.
int total = 0;
int points;
int game = 1;
cout << "Enter the points for game #" << game << endl;
cin >> points;
while (points !=-1)
{
total += points;
game++;
cout << "Enter the points for game #" << game << endl;
cin >> points;
}
This second loop continues on towards infinity until the value -1 is entered, and then it stops without the need for a break;. My first loop however will not stop when the sentinel value is entered unless the break is included.
Why is that?
While statement always repeat until the set condition get to false. In your first code example
while (temp != -1 && temp < 5)
Here, the while loop will exit if temp is -1 or temp is equal to 5. But, you insert break in your code which is will stop or force your while loop condition to stop.
while (condition) {
// Some code.
// Even if the condition true, it will stop because of break.
break;
}
In your second code, the condition set to
while (points !=-1)
so the while will only stop or exit, if the points variable has value of -1.
After understand the basic, you will find the answer for your question on why on the first while it didn't stop if there is no break;. The answer is because the condition on that while is still true so that the while execute again.
break always breaks the loop when it´s called.
In your first loop, however, you´re reading menuItem, no temp.
So, if you in enter -1 menuItem equals -1, no temp.
When the condition is true or false, how can I make it return back and ask the question again, making the user re-enter the value?
Here is what I want to implement:
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int main()
{
int n;
cout<<"Enter numbers. Press 5 to stop: ";
cin>>n;
bool tr=true;
while(tr)
{
if(n!=5)
cout<<"You entered "<<n; //How to make it return again, since its false? I keep getting infinite loops :( ;
else
tr=false;
}
return 0;
}
You need to prompt the user in the while loop, so that it occurs in each iteration:
int n;
bool tr = true;
while(tr)
{
cout << "Enter numbers. Press 5 to stop: ";
cin >> n;
if(n!=5) {
cout << "You entered " << n;
} else {
tr = false;
}
}
Just put all your code (except 'n' and 'tr' definition) in while loop as follow:
int main()
{
int n;
bool tr=true;
while(tr)
{
cout<<"Enter numbers. Press 5 to stop: ";
cin>>n;
if(n!=5)
cout<<"You entered "<<n;
else
tr=false;
}
return 0;
}
The other answers all work, and there is something to be learned about improving program flow from them, but I believe the trick you're asking for is the continue keyword, which skips the remainder of this iteration of the loop.
bool tr = true;
int n;
while (tr)
{
cout << "Enter numbers...";
cin >> n;
if (n != 5)
continue;
else
tr = false;
}
EDIT Part 1: On the continue keyword.
You want to make your code as readable as possible. In this example, its use is unnecessary (as the other posters have shown); but it is the answer to the question "How do I skip the rest of processing in this iteration of my loop and continue to the next iteration?". Usually, such flow-breaking directives actually make code harder to read; but sometimes the opposite is true. Anything (or, at least, almost anything) that can be accomplished with continue or break, can be accomplished without them, so if you're going to use them, you want to have a definite reason for doing so. Usually, when I use continue, it's because I'm looping through a collection of inputs and I want to skip processing the loop whenever the input isn't in the format I'm expecting. Something like this (pseudo-code)...
foreach (Input i in ReceivedInputs)
{
if (i.isBad())
{
cout << "Bad input";
continue;
}
// Do massive block of calculating here.
}
is easier to read than this...
foreach (Input i in ReceivedInputs)
{
if (i.isBad())
cout << "Bad input";
else
{
// Do massive block of calculating here.
}
}
because the second version makes it harder to track what scope you're in, if you're looking toward the end of the massive block of calculating. In this case, I gain code readability by continue, so I use it. But simple code probably shouldn't use it. The break keyword is similar, though it's a lot easier to come up with examples where break is beneficial.
EDIT Part 2: On multiple iterations
This is just an issue of setting up the loop; there are no magic keywords here. The shortest way I can come up with, is probably something like this:
int n = 0;
int numberToTake = 10;
for ( int numbersTaken = 0; numbersTaken < numberToTake; ++numbersTaken)
{
cout << "Enter numbers...";
int n = 0;
for (cin >> n; n != 5; cin >> n)
cout << "Try again.";
// Do whatever processing on n you want to do here.
}
Though I should point out that, doing it this way, the only value you will ever get from the user will be 5, and if he inputs anything that doesn't fit in an integer, you will get unexpected behavior.
EDIT 3: After reading the comment more thoroughly, I think you're just looking for is the more traditional use of the for loop.
No need for the exra bool variable.
The idiom can be: Infinitely loop until the user enters 5:
for(;;) { // Loops infinitely
cout << "Enter numbers. Press 5 to stop: ";
cin >> n;
if(n == 5)
break; // Exits the loop
cout << "You entered " << n; // Before the if if you want to print 5 as well
}
void GasPump::dispense()
{
bool cont = true;
char stop;
do{
cout << "Press any key, or enter to dispense.\n"
<< "Or press 0 to stop: \n";
cin.get(stop);
gasDispensed = gasDispensed + gasDispensedPerCycle;
charges = costPerGallon*gasDispensed;
displayGasNCharges();
if(stop == 0)
cont = false;
} while(cont);
}
Doing an assignment, this is my first program to write with objects so bear with me.
I just can't get the output of this code to turn out right. I need a way to get out
of the loop, and what I'm using just isn't working. Any suggestions, hints or tips?
Try comparing stop to the zero char.
stop == '0'
Also you can simplify your code by doing this.
void GasPump::dispense()
{
char stop;
do {
cout << "Press any key, or enter to dispense.\n"
<< "Or press 0 to stop: \n";
cin.get(stop);
gasDispensed = gasDispensed + gasDispensedPerCycle;
charges = costPerGallon*gasDispensed;
displayGasNCharges();
} while (stop != '0');
}
In this scenario, you pump gas one extra time after the user hits '0'. Assuming that this is not desired, you have what is known as an "off-by-one error." You can fix this (and eliminate the temporary variable) by rearranging your function as follows:
void GasPump::dispense()
{
while (true) {
cout << "Press any key, or enter to dispense.\n"
<< "Or press 0 to stop: \n";
if (cin.get() == '0')
break;
gasDispensed = gasDispensed + gasDispensedPerCycle;
charges = costPerGallon*gasDispensed;
displayGasNCharges();
}
}
To avoid using a break statement, you can use the following construction:
bool GasPump::shouldDispenseGas()
{
cout << "Press any key, or enter to dispense.\n"
<< "Or press 0 to stop: \n";
return (cin.get() != '0');
}
void GasPump::dispense()
{
while (shouldDispenseGas()) {
gasDispensed = gasDispensed + gasDispensedPerCycle;
charges = costPerGallon*gasDispensed;
displayGasNCharges();
}
}
EDIT (2011 September 27):
#TonyK Just because a language provides a feature doesn't mean that one should use it. The goto statement is a classic example of this.
Granted, with such a simple loop, there's really no difference between using a function and the break. Both are clear. However, when extra features get added a month (or years) later, along with extra conditions for breaking out of the loop, it's very easy to find multiply-nested if statements with complex logic inside a loop that's so large, you have a hard time finding its beginning, much less the exit points. One of the ways to fight this type of code bloat is to write short, simple, and focused functions that are well-named. If you do this, the code documents itself. Compare
while (true)
versus
while (shouldDispenseGas())
Similarly, compare this to the STL for_each algorithm. Sure, std::for_each(v.begin(), v.end(), &foo); is a little shorter than for (int i = 0; i < v.size(); ++i) { ...body of foo()... }. But the real advantage is that it's easier to see what the intent is. In the for_each you immediately see that you will be doing something once, and only once, to each element. In the for loop, you have no idea. The loop counter i may be changed in the loop. A break may be hidden inside as well. By shirking this break statement and embedding the logic in shouldDispenseGas, you immediately understand the conditions under which the loop will continue, and end.