Mar 8, 2016 at 2:58am
Hey everyone! I am curious how I get a program to stop executing once a particular condition has been met. For example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
|
#include <iostream>
using namespace std;
int main()
{
double weight;
cout << "Enter weight" << endl;
cin >> weight;
if (weight > 20)
{
cout << "Sorry, the weight cannot exceed 20lbs.\n";
}
// More code . . .
|
If the weight exceeds 20lbs, how do I get the program to stop instead of executing the rest of the code?
Last edited on Mar 8, 2016 at 3:00am
Mar 8, 2016 at 3:59am
If you just put an else after the if, you can put whatever code you dont want the "weight>0" condition to run.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
|
int main()
{
double weight;
cout << "Enter weight: " << endl;
cin >> weight;
if (weight > 20)
{
cout << "Sorry, weight cannot exceed 20lbs.\n";
}
else
{
//Whatever more code you have . . .
}
return 0;
}
|
Although, you could make it so you ask the user to input a new answer if you wanted. This could be done by
1 2 3 4 5 6 7 8 9 10 11 12 13 14
|
int main()
{
double weight;
cout << "Enter weight: " << endl;
cin >> weight;
while (weight > 20 || weight < 0) //I add this weight<0 condition just from assumption
{
cout << "Sorry, weight must not exceed 20lbs.\n Please enter valid entry";
cin >> weight;
}
//whatever more code you have
return 0;
}
|
Last edited on Mar 8, 2016 at 5:31pm
Mar 8, 2016 at 6:20am
@ Nick, the while loop wont work.
Weight cant be more than 20 AND less than 0 simultaneously.
Mar 8, 2016 at 6:31am
@Nick
On the while loop use ||
instead of &&