Newbie programmer here. I'm finished with this project I was working on, and all of my if and else statements function properly, but only when they are placed at the very top of the code I'm writing.
For example, I started writing this code from if(number == 1) and worked my way down, but I eventually had to cut and paste them at the top, because when I entered a value that wasn't 1 (the first if statement, and thus the top statement that functions), the calculator failed to print anything at all when inputting a value for anything else except the top one. Because 4 is at the top, it works fine, but 1-3 don't work, and if I was to put 1 at the top then 2-4 would not print anything.
Here is a screeshot of the if statements on the bottom that do not print, and also have no debugging signs:
I'm sure it's a small issue that I managed to turn big.
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
int number;
float area1, area2, area3, area4;
int R1;
int trib;
int trih;
int top;
int bott;
int traph;
int majxis;
int minxis;
const float PI= 3.14159;
cout<< "I'm starting my program ";
cout<<"\n1.Circle";
cout<<"\n2.triangle";
cout<<"\n3.trapezoid";
cout<<"\n4.ellipse ";
cout<<"\nEnter the corresponding number of your choice(1-4):";
cin>> number;
if(number <= 0)
{
cout<<"Integer is invalid, try again ";
cin>> number;
}
if(number == 4)
{
cout<<"\nWhat is the length of the semi-major axis of the ellipse? ";
}
cin>> majxis;
if(majxis <=0)
{
cout<<"Invalid value for the semi-major axis, try again: ";
}
else
{
cout<<"What is the length for the semi-minor axis of the ellipse? ";
}
cin>> minxis;
area4= PI*minxis*majxis;
if(minxis <=0)
{
cout<<"Invalid value for the semi-minor axis, try again: ";
}
else
{
cout<<"The area of an ellipse with a semi-major axis of " << majxis<< "and a semi-minor axis of " << minxis << "is " << area4;
}
if(number == 3)
{
cout<<"\nWhat is the length of the top of the trapezoid? ";
}
cin>> top;
if(top <=0 )
{
cout<<"\n Invalid value for top length of trapezoid, try again";
}
else
{
cout<<"\nWhat is the length of the bottom of the trapezoid? ";
}
cin>> bott;
if (bott <= 0)
{
cout<<"Invalid value for bottom length of trapezoid, try again: ";
}
else
{
cout<<"What is the height of the trapezoid? ";
}
cin>>traph;
area3 = (top+bott)*0.5+traph;
if (traph <= 0)
{
cout<<"Invalid value for height of trapezoid";
}
else
{
cout<<"The area of a trapezoid with a bottom of " << bott << "and a top of " << top << "is " << area3;
}
if(number == 2)
{
cout<<"\nWhat is the length of the base of the triangle?";
}
cin>> trib;
if(trib<=0)
{
cout<<"\nInvalid Base of triangle, try again:";
}
else
{
cout<<"\nWhat is the height of the triangle? ";
}
cin>> trih;
area2 = (0.5*trib)*trih;
if(trih<=0)
{
cout<<"\nInvalid height of triangle, try again:";
}
else
{
cout<<"\nThe area of a trangle with a base of " << trib << "and a height of "<< trih <<" is " << area2;
}
if(number == 1)
{
cout<<"\nWhat is the radius of the circle?";
}
cin>> R1;
area1 = PI*(R1 *R1);
if( R1 <=0)
{cout<<"\nRadius must be greater than 0, try again";
cin>> R1;
}
else
{
cout<< "\nThe area of a circle with a radius of " << R1 << " is" << area1;
}
}
It indeed is a small issue. Here is the correct program:
#include <iostream>
#include <iomanip>
int main()
{
int number;
float area1, area2, area3, area4;
int R1;
int trib;
int trih;
int top;
int bott;
int traph;
int majxis;
int minxis;
const float PI = 3.14159;
std::cout << "I'm starting my program ";
std::cout << "\n1.Circle";
std::cout << "\n2.triangle";
std::cout << "\n3.trapezoid";
std::cout << "\n4.ellipse ";
std::cout << "\nEnter the corresponding number of your choice(1-4):";
std::cin >> number;
if (number <= 0)
{
std::cout << "Integer is invalid, try again ";
std::cin >> number;
}
else if (number == 1)
{
std::cout << "\nWhat is the radius of the circle?";
std::cin >> R1;
area1 = PI * (R1 * R1);
if (R1 <= 0)
{
std::cout << "\nRadius must be greater than 0, try again";
std::cin >> R1;
}
else
{
std::cout << "\nThe area of a circle with a radius of " << R1 << " is" << area1;
}
}
else if (number == 2)
{
std::cout << "\nWhat is the length of the base of the triangle?";
std::cin >> trib;
if (trib <= 0)
{
std::cout << "\nInvalid Base of triangle, try again:";
}
else
{
std::cout << "\nWhat is the height of the triangle? ";
}
std::cin >> trih;
area2 = (0.5 * trib) * trih;
if (trih <= 0)
{
std::cout << "\nInvalid height of triangle, try again:";
}
else
{
std::cout << "\nThe area of a trangle with a base of " << trib << "and a height of " << trih << " is " << area2;
}
}
else if (number == 3)
{
std::cout << "\nWhat is the length of the top of the trapezoid? ";
std::cin >> top;
if (top <= 0)
{
std::cout << "\n Invalid value for top length of trapezoid, try again";
}
else
{
std::cout << "\nWhat is the length of the bottom of the trapezoid? ";
}
std::cin >> bott;
if (bott <= 0)
{
std::cout << "Invalid value for bottom length of trapezoid, try again: ";
}
else
{
std::cout << "What is the height of the trapezoid? ";
}
std::cin >> traph;
area3 = (top + bott) * 0.5 + traph;
if (traph <= 0)
{
std::cout << "Invalid value for height of trapezoid";
}
else
{
std::cout << "The area of a trapezoid with a bottom of " << bott << "and a top of " << top << "is " << area3;
}
}
else if (number == 4)
{
std::cout << "\nWhat is the length of the semi-major axis of the ellipse? ";
std::cin >> majxis;
if (majxis <= 0)
{
std::cout << "Invalid value for the semi-major axis, try again: ";
}
else
{
std::cout << "What is the length for the semi-minor axis of the ellipse? ";
}
std::cin >> minxis;
area4 = PI * minxis * majxis;
if (minxis <= 0)
{
std::cout << "Invalid value for the semi-minor axis, try again: ";
}
else
{
std::cout << "The area of an ellipse with a semi-major axis of " << majxis << "and a semi-minor axis of " << minxis << "is " << area4;
}
}
}
Explanation: Let's take an example of the area of eclipse (number == 4). In your code, you have made the following if condition:
if(number == 4)
{
cout<<"\nWhat is the length of the semi-major axis of the ellipse? ";
}
This means if number == 4 then print - "\nWhat is the length of the semi-major axis of the ellipse? " but all of the code after it is outside the if condition's {} brackets, and thus is not considered as a part of the if statement. It will be called anyways even if number != 4. Now, in my code, I've done this:
else if (number == 4)
{
std::cout << "\nWhat is the length of the semi-major axis of the ellipse? ";
std::cin >> majxis;
if (majxis <= 0)
{
std::cout << "Invalid value for the semi-major axis, try again: ";
}
else
{
std::cout << "What is the length for the semi-minor axis of the ellipse? ";
}
std::cin >> minxis;
area4 = PI * minxis * majxis;
if (minxis <= 0)
{
std::cout << "Invalid value for the semi-minor axis, try again: ";
}
else
{
std::cout << "The area of an ellipse with a semi-major axis of " << majxis << "and a semi-minor axis of " << minxis << "is " << area4;
}
}
Here, all of the code related to the area of the eclipse is all part of the if (number == 4) statement because it is present between the brackets {} of the if (number == 4) statement.
Apply this to all 4 cases and you get the correct program.
Also, it would be better to refactor your code as such:
#include <iostream>
#include <iomanip>
const float PI = 3.14159;
void areaof_circle()
{
float area;
int R1;
std::cout << "\nWhat is the radius of the circle?";
std::cin >> R1;
area = PI * (R1 * R1);
if (R1 <= 0)
{
std::cout << "\nRadius must be greater than 0, try again";
std::cin >> R1;
}
else
{
std::cout << "\nThe area of a circle with a radius of " << R1 << " is" << area;
}
}
void areaof_triangle()
{
float area;
int trib, trih;
std::cout << "\nWhat is the length of the base of the triangle?";
std::cin >> trib;
if (trib <= 0)
{
std::cout << "\nInvalid Base of triangle, try again:";
}
else
{
std::cout << "\nWhat is the height of the triangle? ";
}
std::cin >> trih;
area = (0.5 * trib) * trih;
if (trih <= 0)
{
std::cout << "\nInvalid height of triangle, try again:";
}
else
{
std::cout << "\nThe area of a trangle with a base of " << trib << "and a height of " << trih << " is " << area;
}
}
void areaof_trapezoid()
{
float area;
int top, bott, traph;
std::cout << "\nWhat is the length of the top of the trapezoid? ";
std::cin >> top;
if (top <= 0)
{
std::cout << "\n Invalid value for top length of trapezoid, try again";
}
else
{
std::cout << "\nWhat is the length of the bottom of the trapezoid? ";
}
std::cin >> bott;
if (bott <= 0)
{
std::cout << "Invalid value for bottom length of trapezoid, try again: ";
}
else
{
std::cout << "What is the height of the trapezoid? ";
}
std::cin >> traph;
area = (top + bott) * 0.5 + traph;
if (traph <= 0)
{
std::cout << "Invalid value for height of trapezoid";
}
else
{
std::cout << "The area of a trapezoid with a bottom of " << bott << "and a top of " << top << "is " << area;
}
}
void areaof_ellipse()
{
float area;
int majxis, minxis;
std::cout << "\nWhat is the length of the semi-major axis of the ellipse? ";
std::cin >> majxis;
if (majxis <= 0)
{
std::cout << "Invalid value for the semi-major axis, try again: ";
}
else
{
std::cout << "What is the length for the semi-minor axis of the ellipse? ";
}
std::cin >> minxis;
area = PI * minxis * majxis;
if (minxis <= 0)
{
std::cout << "Invalid value for the semi-minor axis, try again: ";
}
else
{
std::cout << "The area of an ellipse with a semi-major axis of " << majxis << "and a semi-minor axis of " << minxis << "is " << area;
}
}
int main()
{
int number;
const float PI = 3.14159;
std::cout << "I'm starting my program ";
std::cout << "\n1.Circle";
std::cout << "\n2.triangle";
std::cout << "\n3.trapezoid";
std::cout << "\n4.ellipse ";
std::cout << "\nEnter the corresponding number of your choice(1-4):";
std::cin >> number;
if (number <= 0)
{
std::cout << "Integer is invalid, try again ";
std::cin >> number;
}
else if (number == 1)
{
areaof_circle();
}
else if (number == 2)
{
areaof_triangle();
}
else if (number == 3)
{
areaof_trapezoid();
}
else if (number == 4)
{
areaof_ellipse();
}
}
Also, don't use the following in your programs:
using namespace std;
...as it's considered as bad practice. Use std:: every time instead.
There is a problem with your if statement..
as the well defined answer is already given, I am simplifying your code's readability and suggesting more better way to do this..
NOTE: Considering you're new bie.
Create Functions to handle different quadrilaterals
#include <iostream>
#include <iomanip>
using namespace std;
float area1, area2, area3, area4;
int R1;
int trib;
int trih;
int top;
int bott;
int traph;
int majxis;
int minxis;
const float PI= 3.14159;
void handle_circle();
void handle_ellipse();
void handle_triangle();
void handle_trapizoid();
int main()
{
int number;
cout<< "I'm starting my program ";
cout<<"\n1.Circle";
cout<<"\n2.triangle";
cout<<"\n3.trapezoid";
cout<<"\n4.ellipse ";
cout<<"\nEnter the corresponding number of your choice(1-4):";
cin>> number;
if(number <= 0)
{
cout<<"Integer is invalid, try again ";
cin>> number;
}
if(number == 4)
{
handle_ellipse();
}
if(number == 3)
{
handle_trapizoid();
}
if(number == 2)
{
handle_triangle();
}
if(number == 1)
{
handle_circle();
}
}
void handle_trapizoid()
{
cout<<"\nWhat is the length of the top of the trapezoid? ";
cin>> top;
if(top <=0 )
{
cout<<"\n Invalid value for top length of trapezoid, try again";
}
else
{
cout<<"\nWhat is the length of the bottom of the trapezoid? ";
cin>> bott;
}
if (bott <= 0)
{
cout<<"Invalid value for bottom length of trapezoid, try again: ";
}
else
{
cout<<"What is the height of the trapezoid? ";
cin>>traph;
area3 = (top+bott)*0.5+traph;
}
if (traph <= 0)
{
cout<<"Invalid value for height of trapezoid";
}
else
{
cout<<"The area of a trapezoid with a bottom of " << bott << "and a top of " << top << "is " << area3;
}
}
void handle_ellipse()
{
cout<<"\nWhat is the length of the semi-major axis of the ellipse? ";
cin>> majxis;
if(majxis <=0)
{
cout<<"Invalid value for the semi-major axis, try again: ";
}
else
{
cout<<"What is the length for the semi-minor axis of the ellipse? ";
cin>> minxis;
area4= PI*minxis*majxis;
}
if(minxis <=0)
{
cout<<"Invalid value for the semi-minor axis, try again: ";
}
else
{
cout<<"The area of an ellipse with a semi-major axis of " << majxis<< "and a semi-minor axis of " << minxis << "is " << area4;
}
}
void handle_triangle()
{
cout<<"\nWhat is the length of the base of the triangle?";
cin>> trib;
if(trib<=0)
{
cout<<"\nInvalid Base of triangle, try again:";
}
else
{
cout<<"\nWhat is the height of the triangle? ";
cin>> trih;
area2 = (0.5*trib)*trih;
}
if(trih<=0)
{
cout<<"\nInvalid height of triangle, try again:";
}
else
{
cout<<"\nThe area of a trangle with a base of " << trib << "and a height of "<< trih <<" is " << area2;
}
}
void handle_circle()
{
cout<<"\nWhat is the radius of the circle?";
cin>> R1;
area1 = PI*(R1 *R1);
if( R1 <=0)
{cout<<"\nRadius must be greater than 0, try again";
cin>> R1;
}
else
{
cout<< "\nThe area of a circle with a radius of " << R1 << " is" << area1;
}
}
Also you can use switch statement as it is more faster than if statements
#include <iostream>
#include <iomanip>
using namespace std;
float area1, area2, area3, area4;
int R1;
int trib;
int trih;
int top;
int bott;
int traph;
int majxis;
int minxis;
const float PI= 3.14159;
void handle_circle();
void handle_ellipse();
void handle_triangle();
void handle_trapizoid();
int main()
{
int number;
cout<< "I'm starting my program ";
cout<<"\n1.Circle";
cout<<"\n2.triangle";
cout<<"\n3.trapezoid";
cout<<"\n4.ellipse ";
cout<<"\nEnter the corresponding number of your choice(1-4):";
cin>> number;
switch(number)
{
case 1:
handle_circle();
break;
case 2:
handle_triangle();
break;
case 3:
handle_ellipse();
break;
case 4:
handle_trapizoid();
break;
default:
{
cout<<"Integer is invalid, try again ";
}
}
}
void handle_trapizoid()
{
cout<<"\nWhat is the length of the top of the trapezoid? ";
cin>> top;
if(top <=0 )
{
cout<<"\n Invalid value for top length of trapezoid, try again";
}
else
{
cout<<"\nWhat is the length of the bottom of the trapezoid? ";
cin>> bott;
}
if (bott <= 0)
{
cout<<"Invalid value for bottom length of trapezoid, try again: ";
}
else
{
cout<<"What is the height of the trapezoid? ";
cin>>traph;
area3 = (top+bott)*0.5+traph;
}
if (traph <= 0)
{
cout<<"Invalid value for height of trapezoid";
}
else
{
cout<<"The area of a trapezoid with a bottom of " << bott << "and a top of " << top << "is " << area3;
}
}
void handle_ellipse()
{
cout<<"\nWhat is the length of the semi-major axis of the ellipse? ";
cin>> majxis;
if(majxis <=0)
{
cout<<"Invalid value for the semi-major axis, try again: ";
}
else
{
cout<<"What is the length for the semi-minor axis of the ellipse? ";
cin>> minxis;
area4= PI*minxis*majxis;
}
if(minxis <=0)
{
cout<<"Invalid value for the semi-minor axis, try again: ";
}
else
{
cout<<"The area of an ellipse with a semi-major axis of " << majxis<< "and a semi-minor axis of " << minxis << "is " << area4;
}
}
void handle_triangle()
{
cout<<"\nWhat is the length of the base of the triangle?";
cin>> trib;
if(trib<=0)
{
cout<<"\nInvalid Base of triangle, try again:";
}
else
{
cout<<"\nWhat is the height of the triangle? ";
cin>> trih;
area2 = (0.5*trib)*trih;
}
if(trih<=0)
{
cout<<"\nInvalid height of triangle, try again:";
}
else
{
cout<<"\nThe area of a trangle with a base of " << trib << "and a height of "<< trih <<" is " << area2;
}
}
void handle_circle()
{
cout<<"\nWhat is the radius of the circle?";
cin>> R1;
area1 = PI*(R1 *R1);
if( R1 <=0)
{cout<<"\nRadius must be greater than 0, try again";
cin>> R1;
}
else
{
cout<< "\nThe area of a circle with a radius of " << R1 << " is" << area1;
}
}
Related
I am trying to create a user-define function in C++ to prevent an endless loop from inputting an incorrect input for a double variable and check if an input is negative or zero. If that's the case the function will go into a do-while loop to ask the user to try again until the value is no longer something other than a double, negative, or zero.
The function fix() is the the user-defined
#include <iostream>
#include <string>
#include <iomanip>
#include <cmath>
using namespace std;
string fix(double x)
{
string B_error = "B cannot be zero or negative. Please try again: ";
string H_error = "H cannot be zero or negative. Please try again: ";
string h_error = "b cannot be zero or negative. Please try again: ";
string b_error = "h cannot be zero or negative. Please try again: ";
string r_error = "r cannot be zero or negative. Please try again: ";
string y_error;
while (!(cin >> x))
{
if (cin.fail())
{
cout << "Erroneous input. Please try again:\n";
cin.clear(); // used to prevent an endless loop if an input type is not an integer
cin.ignore(10000, '\n');
}
}
if (x == 'B')
{
y_error = B_error;
if (x <= 0)
{
do
{
return y_error;
cin >> x;
}
while (x <= 0);
}
}
return 0;
}
int main()
{
int selection;
double I, B, H, b, h, r, fix(double);
cout << "Please select the type of beam:\n"
<< "1) I-Beam\n"
<< "2) Rectangular Beam\n"
<< "3) Cylindrical Beam\n";
while (!(cin >> selection) || selection < 1 || selection > 3)
{
if (cin.fail() || selection < 1 || selection > 3)
{
cout << "Erroneous input. Please try again:\n";
cin.clear(); // used to prevent an endless loop if an input type is not an integer
cin.ignore(10000, '\n');
}
}
switch (selection)
{
case 1:
cout << "You have selected I-beam. All inputs must be in inches.\n"
<< "Please input the value for B: ";
fix(B);
cout << "Please input the value for H: ";
fix(H);
if (H <= 0)
{
do
{
cout << "H cannot be zero or negative. Please try again: ";
cin >> H;
}
while (H <= 0);
}
cout << "Please input the value for b: ";
fix(b);
if (b <= 0)
{
do
{
cout << "b cannot be zero or negative. Please try again: ";
cin >> b;
}
while (b <= 0);
}
else if (b > B)
{
do
{
cout << "b cannot be larger than B. Please try again: ";
cin >> b;
}
while (b > B);
}
cout << "Please input the value for h: ";
fix(h);
if (h <= 0)
{
do
{
cout << "h cannot be zero or negative. Please try again: ";
cin >> h;
}
while (h <= 0);
}
else if (h > H)
{
do
{
cout << "h cannot be larger than H. Please try again: ";
cin >> H;
}
while (h > H);
}
I = (B*H*H*H - b*h*h*h)/12.;
cout << "\nResults for an I-beam with B = " << B
<< ", H = " << H << ", b = " << b << ", and h = " << h << endl;
cout << setfill('-') << setw(32) << "" << endl;
break;
case 2:
cout << "You have selected rectangular beam. All inputs must be in inches.\n"
<< "Please input the value for b: ";
fix(b);
if (b <= 0)
{
do
{
cout << "b cannot be zero or negative. Please try again: ";
cin >> b;
}
while (b <= 0);
}
cout << "Please input the value for h: ";
fix(h);
if (h <= 0)
{
do
{
cout << "h cannot be zero or negative. Please try again: ";
cin >> h;
}
while (h <= 0);
}
I = b*h*h*h/12.;
cout << "\nResults for a rectangular beam with b = " << b << " and h = " << h << endl;
cout << setfill('-') << setw(32) << "" << endl;
break;
case 3:
cout << "You have selected cylindrical beam. All inputs must be in inches.\n"
<< "Please input the value of r: ";
fix(r);
if (r <= 0)
{
do
{
cout << "r cannot be zero or negative. Please try again: ";
cin >> r;
}
while (r <= 0);
}
I = M_PI*pow(r,4)/4.;
cout << "\nResults for a cylindrical beam with r = " << r << endl;
cout << setfill('-') << setw(32) << "" << endl;
break;
}
cout << "The value of the moment of inertia for this beam is: " << I << "in^4" << "\n\n";
return 0;
}
I removed the issues. You are confusing instances of classes with functions. Functions don't have to be initialized, instances have to if they are outside of the class.
I wrote some comments along the code. It is still not beautiful but at least it works.
string FUNCTION(double) btw. means the function only can or should return a "string". If you are returning nothing the function is written like so void FUNCTION(double).
If your return f.e. a string you have to write something that is receiving the returned string like so:
#include <iostream>
/*
std::string returning_value;
returning_value = FUNCTION(1.0);
*/
//or
std::string FUNCTION(double function_a); //prototype of the function
//you need this if you write the function underneath the main() function
//The main function is returning "return 0" so since "0" is an "int"
//meaning main is always "int main()" btw. because it is a function,
//just not some function but the "main function" thats called by the OS
int main()
{
std::string returning_value;
double a = 0.1; //initializing with 0.1
returning_value = FUNCTION(a);
std::cout << returning_value << std::endl;
//and in both cases the function would look like:
return 0;
}
std::string FUNCTION(double function_a)
{
std::string returning_value_a = "This is a string that will be returned";
if(function_a == 0.1)
{
returning_value_a = "This is another string";
}
return returning_value_a;
}
Your code with the least amount fixed that you got it at least working
and you can test with how to get the right output you want to get. Have fun :) Hope my answer helps you :)
#include <iostream>
#include <string>
#include <iomanip>
#include <cmath>
using namespace std;
void fix(double x)
{
string B_error = "B cannot be zero or negative. Please try again: ";
string H_error = "H cannot be zero or negative. Please try again: ";
string h_error = "b cannot be zero or negative. Please try again: ";
string b_error = "h cannot be zero or negative. Please try again: ";
string r_error = "r cannot be zero or negative. Please try again: ";
string y_error;
while (!(cin >> x))
{
if (cin.fail())
{
cout << "Erroneous input. Please try again:\n";
cin.clear(); // used to prevent an endless loop if an input type is not an integer
cin.ignore(10000, '\n');
}
}
//warning: comparing floating point with == or != is unsafe
if (x == 'B')
{
y_error = B_error;
if (x <= 0)
{
do
{
cin >> x;
}
while (x <= 0);
}
}
}
int main()
{
int selection;
double I, B, H, b, h, r;
//You need to initialize the variables with a value
I = 1.0;
B = 1.0;
H = 1.0;
b = 1.0;
h = 1.0;
r = 1.0;
//functions don't need to be initialized, thats for Instanzes of classes
//double fix(double);
cout << "Please select the type of beam:\n"
<< "1) I-Beam\n"
<< "2) Rectangular Beam\n"
<< "3) Cylindrical Beam\n";
while (!(cin >> selection) || selection < 1 || selection > 3)
{
if (cin.fail() || selection < 1 || selection > 3)
{
cout << "Erroneous input. Please try again:\n";
cin.clear(); // used to prevent an endless loop if an input type is not an integer
cin.ignore(10000, '\n');
}
}
switch (selection)
{
case 1:
cout << "You have selected I-beam. All inputs must be in inches.\n"
<< "Please input the value for B: ";
fix(B);
cout << "Please input the value for H: ";
fix(H);
if (H <= 0)
{
do
{
cout << "H cannot be zero or negative. Please try again: ";
cin >> H;
}
while (H <= 0);
}
cout << "Please input the value for b: ";
fix(b);
if (b <= 0)
{
do
{
cout << "b cannot be zero or negative. Please try again: ";
cin >> b;
}
while (b <= 0);
}
else if (b > B)
{
do
{
cout << "b cannot be larger than B. Please try again: ";
cin >> b;
}
while (b > B);
}
cout << "Please input the value for h: ";
fix(h);
if (h <= 0)
{
do
{
cout << "h cannot be zero or negative. Please try again: ";
cin >> h;
}
while (h <= 0);
}
else if (h > H)
{
do
{
cout << "h cannot be larger than H. Please try again: ";
cin >> H;
}
while (h > H);
}
I = (B*H*H*H - b*h*h*h)/12.;
cout << "\nResults for an I-beam with B = " << B
<< ", H = " << H << ", b = " << b << ", and h = " << h << endl;
cout << setfill('-') << setw(32) << "" << endl;
break;
case 2:
cout << "You have selected rectangular beam. All inputs must be in inches.\n"
<< "Please input the value for b: ";
fix(b);
if (b <= 0)
{
do
{
cout << "b cannot be zero or negative. Please try again: ";
cin >> b;
}
while (b <= 0);
}
cout << "Please input the value for h: ";
fix(h);
if (h <= 0)
{
do
{
cout << "h cannot be zero or negative. Please try again: ";
cin >> h;
}
while (h <= 0);
}
I = b*h*h*h/12.;
cout << "\nResults for a rectangular beam with b = " << b << " and h = " << h << endl;
cout << setfill('-') << setw(32) << "" << endl;
break;
case 3:
cout << "You have selected cylindrical beam. All inputs must be in inches.\n"
<< "Please input the value of r: ";
fix(r);
if (r <= 0)
{
do
{
cout << "r cannot be zero or negative. Please try again: ";
cin >> r;
}
while (r <= 0);
}
I = M_PI*pow(r,4)/4.;
cout << "\nResults for a cylindrical beam with r = " << r << endl;
cout << setfill('-') << setw(32) << "" << endl;
break;
}
cout << "The value of the moment of inertia for this beam is: " << I << "in^4" << "\n\n";
return 0;
}
So, I had to add another function to check if B < b and H < h and add a do-while loop after the while loop in the fix function.
Here's my code with the fix:
#include <iostream>
#include <string>
#include <iomanip>
#include <cmath>
using namespace std;
void fix(double &x)
{
while (!(cin >> x))
{
if (cin.fail())
{
cout << "Erroneous input. Please try again:\n";
cin.clear(); // used to prevent an endless loop if an input type is not a double
cin.ignore(10000, '\n');
}
}
string return_x = "This cannot be zero or negative. Please try again: ";
while (x <= 0)
{
cout << return_x << endl;
cin >> x;
}
}
void fix2(double &x, double &y)
{
while (x < y)
{
cout << x << " cannot be less than " << y << endl;
fix(y);
}
}
int main()
{
int selection;
double I = 1.0;
double B = 1.0;
double H = 1.0;
double b = 1.0;
double h = 1.0;
double r = 1.0;
cout << "Please select the type of beam:\n"
<< "1) I-Beam\n"
<< "2) Rectangular Beam\n"
<< "3) Cylindrical Beam\n";
while (!(cin >> selection) || selection < 1 || selection > 3)
{
if (cin.fail() || selection < 1 || selection > 3)
{
cout << "Erroneous input. Please try again:\n";
cin.clear(); // used to prevent an endless loop if an input type is not an integer
cin.ignore(10000, '\n');
}
}
switch (selection)
{
case 1:
cout << "You have selected I-beam. All inputs must be in inches.\n"
<< "Please input the value for B: ";
fix(B);
cout << "Please input the value for H: ";
fix(H);
cout << "Please input the value for b: ";
fix(b);
fix2(B, b);
cout << "Please input the value for h: ";
fix(h);
fix2(H, h);
I = (B * H * H * H - b * h * h * h) / 12.;
cout << "\nResults for an I-beam with B = " << B << ", H = " << H
<< ", b = " << b << ", and h = " << h << endl;
cout << setfill('-') << setw(32) << "" << endl;
break;
case 2:
cout << "You have selected rectangular beam. All inputs must be in inches.\n"
<< "Please input the value for b: ";
fix(b);
cout << "Please input the value for h: ";
fix(h);
I = b * h * h * h / 12.;
cout << "\nResults for a rectangular beam with b = " << b
<< " and h = " << h << endl;
cout << setfill('-') << setw(32) << "" << endl;
break;
case 3:
cout << "You have selected cylindrical beam. All inputs must be in inches.\n"
<< "Please input the value of r: ";
fix(r);
I = M_PI * pow(r, 4) / 4.;
cout << "\nResults for a cylindrical beam with r = " << r << endl;
cout << setfill('-') << setw(32) << "" << endl;
break;
}
cout << "The value of the moment of inertia for this beam is: " << I
<< "in^4" << "\n\n";
return 0;
}
I have an assignment to create a menu-based program to calculate area of several shapes using user-defined function. My code creates an infinite loop when a user input a char instead of a number. What should I do? Also, I would like if someone could evaluate my code, Is there anything I should change or modify? I'm still new to C++.
Input:
1. a
2. j
#include <iostream>
#include <cmath>
using namespace std;
float Circle(double r1);
float Rectangle(double length, double width);
float Triangle(float s1, float s2, float s3);
float Cylinder(double height, double r2);
float Square(double l1, double l2);
int main()
{
char o, d;
do
{//List of what shapes the program can calculate
cout << " Calculator for area of shapes " << endl;
cout << endl;
cout << " List of Area: " << endl;
cout << " A. Circle " << endl;
cout << " B. Rectangle " << endl;
cout << " C. Triangle " << endl;
cout << " D. Cylinder " << endl;
cout << " E. Square " << endl;
cout << " X. Exit " << endl;
cout << endl;
//Choose what shape to calculate
cout << " Please enter the area you wish to calculate: ";
cin >> o;
cout << endl;
//Program determine what calculation to use
switch (o)
{
case 'a'://For Circle
case 'A':
double r1;
while (true)
{
cout << " Radius of Circle: ";
cin >> r1;
if (r1 > 0)
{
Circle(r1);
cout << endl;
break;
}
else
{// If the input is less than 0 an error message will occur and user need to reinput the data
cout << " ERROR! NOT A CIRCLE. Please input value more than 0." << endl;
}
}
break;
case 'b'://For Rectangle
case 'B':
double length, width;
while (true)
{
cout << " Length of Rectangle: ";
cin >> length;
cout << " Width of Rectangle: ";
cin >> width;
if (length > 0 && width > 0)
{
Rectangle(length, width);
cout << endl;
break;
}
else
{
cout << " ERROR! Not A Rectangle. Please input value more than 0 " << endl;
}
}
case 'c'://For Triangle
case 'C':
float s1, s2, s3;
while (true)
{
cout << " Length of side A: ";
cin >> s1;
cout << " Length of side B: ";
cin >> s2;
cout << " Length of side C: ";
cin >> s3;
if ((s1 + s2) > s3 && (s2 + s3) > s1 && (s3 + s1) > s2)
{
Triangle(s1, s2, s3);
cout << endl;
break;
}
else
{
cout << " ERROR!!! NOT A TRIANGLE. Please input value more than 0 " << endl;
}
}
case 'd'://For Cylinder
case 'D':
double height, r2;
cout << " Radius of Cylinder: ";
cin >> r2;
cout << "Height of Cylinder: ";
cin >> height;
while (true)
{
if (r2 > 0 && height > 0)
{
Cylinder(height, r2);
break;
}
else
{
cout << " ERROR!!! NOT A CYLINDER. Please input value more than 0 " << endl;
}
}
case 'e'://For Square
case 'E':
double l1, l2;
while (true)
{
cout << " Length of side 1: ";
cin >> l1;
cout << " Length of side 2: ";
cin >> l2;
if (l1 > 0 && l2 > 0)
{
Square(l1, l2);
break;
}
else
{
cout << " ERROR!!! NOT A SQUARE. " << endl;
}
}
case 'x':
case 'X'://Program end
cout << " ---- PROGRAM END ---- ";
exit(0);
default: // Error message occur if user don't
cout << " ERROR!! PLEASE INPUT RIGHT LETTER ";
cout << endl;
}
// user can choose to use program again or not
cout << " Do you wish to continue using the calculator?(Y/N): ";
cin >> d;
cout << endl;
} while (d == 'y' || d == 'Y');
if (d == 'n' || d == 'N')
{
cout << " ---- PROGRAM END ---- ";
}
return 0;
}
float Circle(double r1)//Calculation for Circle
{
double area;
const double pi = 3.14;
area = pi * (r1 * r1); //Formula for area of Circle
cout << " Area of Circle: " << area;
cout << endl;
return 0;
}
float Rectangle(double length, double width)//Calculation for Rectangle
{
double area;
area = length * width;//Formula for area of Rectangle
cout << " Area of Rectangle: " << area;
cout << endl;
return 0;
}
float Triangle(float s1, float s2, float s3)//Calculation for Triangle
{
float area, s;
s = (s1 + s2 + s3) / 2;
area = sqrt(s * (s - s1) * (s - s2) * (s - s3));//Formula for area of Triangle
cout << " Area of triangle: " << area << endl;
cout << endl;
return 0;
}
float Cylinder(double height, double r2)//Calculation for Cylinder
{
double area;
const double pi = 3.14;
area = 2 * pi * r2 * (r2 + height);//Formula for area of Cylinder
cout << endl;
return 0;
}
float Square(double l1, double l2)//Calculation for Square
{
double area;
area = l1 * l2;//Formula for area of Square
cout << " Area of Square: " << area << endl;
cout << endl;
return 0;
}
With float r1; cin >> r1; and non-numeric input, there is nothing consumed from input. Repeating cin >> r1 results in an endless loop.
What to do?
Check whether cin >> r1 was successful: if (cin >> r1) { /* process r1 */ }
If not successful, do something to consume wrong input: else { cin.clear(); cin.ignore(); }
std::ios::clear()
Sets the stream error state flags by assigning them the value of state. By default, assigns std::ios_base::goodbit which has the effect of clearing all error state flags.
std::istream::ignore()
Extracts and discards characters from the input stream until and including delim.
Example:
#include <iostream>
#include <limits>
int main()
{
double value = 0.0;
for (;;) {
std::cout << "Value: ";
if (std::cin >> value) {
break; // success -> bail out of loop
} else {
std::cerr << "Wrong input!\n";
std::cin.clear(); // reset state
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); // consume wrong input
}
}
std::cout << "Value: " << value << '\n';
return 0;
}
Output:
Value: Hello↵
Wrong input!
Value: 1.23↵
Value: 1.23
Live Demo on coliru
So I have written a small program to work out the perimeter of simple shapes (very new to coding so keeping it simple). I am now stuck though
the code works up too triangle and I can't for the life of me work out how to get the last logical operator to work!!!? As always greatly appreciate your time and advice.
Best regards, Jake.
#include <iostream>
#include <string>
using namespace std;
int main ()
{
int length;
int Diameter;
float Pi = 3.14;
string Shape;
string Square = "Square";
string Triangle = "Triangle";
string Circle = "Circle";
cout <<"=======================" << endl;
cout <<"=Welcome to Perimeters=" << endl;
cout <<"#######################" << endl;
cout <<"###|Select A Shape|####" << endl;
cout <<"=======================" << endl;
cout <<"= | Circle | =" << endl;
cout <<"= | Triangle | =" << endl;
cout <<"= | Square | =" << endl;
cout <<"=======================" << endl;
cout <<"Enter Shape >; ";
cin >> Shape;
if (Shape == "Square") {
cout << "Enter Length of Side >: ";
cin >> length;
cout << "Perimeter = " ;
cout << length * 4 <<endl;
} else {
(Shape == "Triangle"){
cout << "Enter Length of Side >: ";
cin >> length;
cout << "Perimeter = " ;
cout << length * 3 <<endl;
}
}
else {
(Shape == "Circle") {
cout << "Enter Diameter >: ";
cin >> Diameter;
cout << "Perimeter = " ;
cout << Diameter * Pi <<endl;
}
}
return 0;
}
You are not writing the else-if statement correctly. It should be in the form:
if(boolean expression) {}
else if (boolean expression) {} // as many else ifs as you need
else {} // optional
Therefore your else if conditionals should be:
if (Shape == "Square") {
cout << "Enter Length of Side >: ";
cin >> length;
cout << "Perimeter = " ;
cout << length * 4 <<endl;
} else if (Shape == "Triangle"){
// and so on...
} else {
cout << "Invalid shape entered.";
}
Additionally, PI isn't 3.14. Include <math.h> and use M_PI.
You need to work on your code formatting...
Use else if insead of else.
if (Shape == "Square") {
cout << "Enter Length of Side >: ";
cin >> length;
cout << "Perimeter = " ;
cout << length * 4 <<endl;
}
else if (Shape == "Triangle"){
cout << "Enter Length of Side >: ";
cin >> length;
cout << "Perimeter = " ;
cout << length * 3 <<endl;
}
else if (Shape == "Circle") {
(Shape == "Circle")
cout << "Enter Diameter >: ";
cin >> Diameter;
cout << "Perimeter = " ;
cout << Diameter * Pi <<endl;
}
else{
cout << "invalid shape name" << endl;
}
Hello You have to write else if as below.
#include <iostream>
#include <string>
using namespace std;
int main ()
{
int length;
int Diameter;
float Pi = 3.14;
string Shape;
string Square = "Square";
string Triangle = "Triangle";
string Circle = "Circle"; **strong text**
cout <<"=======================" << endl;
cout <<"=Welcome to Perimeters=" << endl;
cout <<"#######################" << endl;
cout <<"###|Select A Shape|####" << endl;
cout <<"=======================" << endl;
cout <<"= | Circle | =" << endl;
cout <<"= | Triangle | =" << endl;
cout <<"= | Square | =" << endl;
cout <<"=======================" << endl;
cout <<"Enter Shape >; ";
cin >> Shape;
if (Shape == "Square") {
cout << "Enter Length of Side >: ";
cin >> length;
cout << "Perimeter = " ;
cout << length * 4 <<endl;
} else if (Shape == "Triangle"){
cout << "Enter Length of Side >: ";
cin >> length;
cout << "Perimeter = " ;
cout << length * 3 <<endl;
} else if (Shape == "Circle") {
cout << "Enter Diameter >: ";
cin >> Diameter;
cout << "Perimeter = " ;
cout << Diameter * Pi <<endl;
}
return 0;
}
Hope this will help you
I have this code where in option lists will display when run. my problem is when I enter number 2, the option 2 program doesn't work well. It just go directly to asking the amount paid instead of asking first the cost of purchase.
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
float circle (float a)
{
float z;
z = 3.141593 * (a * a);
return (z);
}
float square (float b)
{
float y;
y = b * b;
return (y);
}
float rectangle (float c, float d)
{
float x;
x = c * d;
return (x);
}
float triangle (float e, float f)
{
float w;
w = (e * f) / 2;
return (w);
}
void exit ()
{
cout << "THANK YOU! GOODBYE!" << endl;
}
int main()
{
int x;
do
{
cout << "Please choose an option below: \n";
cout << "1. Area of Shapes\n";
cout << "2. Cost of your items\n";
cout << "3. Flood Control\n";
cout << "4. Fibonacci Numbers\n";
cout << "5. Addition Table\n";
cout << "6. Exit\n";
cin >> x;
if (x == 1)
{
system("cls");
float n;
float l;
float m;
float radius;
float side;
float length;
float width;
float base;
float height;
do
{
cout << "1 => Area of Circle" << endl;
cout << "2 => Area of Square" << endl;
cout << "3 => Area of Rectangle" << endl;
cout << "4 => Area of Trian1gle" << endl;
cout << "5 => Return to Main Menu" << endl;
cout << "0 => Exit" << endl;
cout << "Please enter number of your choice: ";
cin >> n;
system("cls");
{
if (n == 0)
{
exit ();
system("pause");
return 0;
}
else if (n == 1)
{
cout << "Enter radius of the circle: ";
cin >> radius;
l = circle (radius);
cout << "Area of the circle is: " << l << endl;
system("pause");
system("cls");
}
else if (n == 2)
{
cout << "Enter side of the square: ";
cin >> side;
cout << "Area of the square is: " << square (side) << endl;
system("pause");
system("cls");
}
else if (n == 3)
{
cout << "Enter length of the rectangle: ";
cin >> length;
cout << "Enter width of the rectangle: ";
cin >> width;
m = rectangle (length, width);
cout << "Area of the rectangle is: " << m << endl;
system("pause");
system("cls");
}
else if (n == 4)
{
cout << "Enter base of the triangle: ";
cin >> base;
cout << "Enter height of the triangle: ";
cin >> height;
cout << "Area of the triangle is: " << triangle (base, height) << endl;
system("pause");
system("cls");
}
else if (n == 5)
{
exit ();
}
else
cout << "Invalid number. Please enter a valid number below" << endl;
}
}
while (n != 0 && n != 5);
cout << endl << endl;
system("pause");
system("cls");
}
else if (x == 2)
{
system("cls");
string mystr;
float cost = 0;
float amount = 0;
float total;
cout << "Total Cost: P";
getline (cin, mystr);
stringstream(mystr) >> cost;
cout << endl;
total = cost * .06;
cout << "Sales Tax Value: P" << total << endl;
cout << endl;
cout << "Cost of Item: P" << cost + total << endl;
cout << endl;
cout << "Amount Paid: P";
getline (cin, mystr);
stringstream(mystr) >> amount;
cout << endl;
cout << "Total Amount Purchased: P" << cost << endl;
cout << "Sales Tax Value: P" << total << endl;
cout << "Total Amount + Sales Tax: P" << cost + total << endl;
cout << "Total Amount Paid: P" << amount << endl;
cout << "Change: P" << amount - (cost + total) << endl;
system("pause");
cout << endl;
cout << "THANK YOU! ENJOY YOUR MEAL!" << endl;
system("pause");
system("cls");
}
else if (x > 6)
cout << "Invalid Input";
else
{
system("pause");
return 0;
}
}
while (x != 6);
system("pause");
return 0;
}
EDIT
For the posters education
You do
switch (n) {
case 1:
//... Code for n == 1 - If long put into another function. If using local variables put code bloc in braces
break;
case 2:
// Diitto for n==2
default: // No match
// All other values of n not listed above
}
What went wrong
Say you type your menu selection:
2<Enter>
Then the content of the std::cin stream will be:
2\n
When your menu selection runs...
cin >> x;
...it reads a number off the line but doesn't consume any trailing whitespace nor the newline, so the remaining state content could be denoted like this:
\n
Then your code for menu option 2 starts running:
cout << "Total Cost: P";
getline (cin, mystr);
...the getline looks at std::cin and finds the left over \n mentioned above, and says "hey, an empty line - I'll set mystr to an empty string". Notice that it did not do what you'd hoped: namely wait for you to type some more input and read that into mystr.
How to fix it
Before calling getline(cin, mystr) you want to remove the left-over \n typed when entering the menu selection. The code changes for that (adding error handling too):
#include <limits>
...
cout << "Total Cost: P";
std::cin.ignore(std::numeric_limits<streamsize>::max(), '\n');
if (!std::getline(std::cin, mystr))
{
std::cerr << "unable to read mystr\n";
exit(1);
}
std::istringstream iss(mystr);
iss >> cost;
if (!iss)
{
std::cerr << "mystr doesn't contain a valid cost number\n";
exit(1);
}
How you could have found the problem
When you get stuck like this, try adding some "trace" statements to print out the values of variables and find where they differ from your expectation... that can at least give you a better idea how to isolate and describe the problem, and what to google for to fix it.
std::out << "mystr '" << mystr << "'\n";`
Try to use error handling like I've illustrated so the program stops (or prompts for better input) when there's a problem parsing the user's input.
I have this code when executed it will let the user choose an option. once the user enters an option the program will be cleared and execute another program. below is the sample. at the bottom is another program of option 1
#include <iostream>
using namespace std;
int main()
{
int a;
cout<<"Please choose an option below: \n";
cout<<"1. Area of Shapes\n";
cout<<"2. Cost of your items\n";
cout<<"3. Flood Control\n";
cout<<"4. Fibonacci Numbers\n";
cout<<"5. Addition Table\n";
cout<<"6. Exit\n";
cin>> a;
system("pause");
return 0;
}
Here is the program for option 1:
#include <iostream>
using namespace std;
float circle (float a)
{
float z;
z = 3.141593*(a*a);
return (z);
}
float square (float b)
{
float y;
y = b * b;
return (y);
}
float rectangle (float c, float d)
{
float x;
x = c * d;
return (x);
}
float triangle (float e, float f)
{
float w;
w = (e * f) / 2;
return (w);
}
void exit ()
{
cout << "THANK YOU! GOODBYE!" <<endl;
}
int main()
{
float n;
float l;
float m;
float radius;
float side;
float length;
float width;
float base;
float height;
do
{
cout << "1 => Area of Circle" <<endl;
cout << "2 => Area of Square" <<endl;
cout << "3 => Area of Rectangle" <<endl;
cout << "4 => Area of Triangle" <<endl;
cout << "0 => Exit" <<endl;
cout << "Please enter number of your choice: ";
cin >> n;
{
if (n==0)
{
exit ();
system("pause");
return 0;
}
else if (n==1)
{
cout << "Enter radius of the circle: ";
cin >> radius;
l = circle (radius);
cout << "Area of the circle is: " <<l <<endl;
}
else if (n==2)
{
cout << "Enter side of the square: ";
cin >> side;
cout << "Area of the square is: " <<square (side) <<endl;
}
else if (n==3)
{
cout << "Enter length of the rectangle: ";
cin >> length;
cout << "Enter width of the rectangle: ";
cin >> width;
m = rectangle (length, width);
cout << "Area of the rectangle is: " <<m <<endl;
}
else if (n==4)
{
cout << "Enter base of the triangle: ";
cin >> base;
cout << "Enter height of the triangle: ";
cin >> height;
cout << "Area of the triangle is: " <<triangle (base, height) <<endl;
}
else
cout << "Invalid number. Please enter a valid number below" <<endl;
}
}
while (n!=0);
cout <<endl <<endl;
system("pause");
return 0;
}
If you truely want to replace the current program with another, look to the exec family of system calls.
Put each "program" in its own file (or not, but it's a good idea to keep them separate).
Rename each "program"'s main to something meaningful, like "areas".
Declare that function in a header.
Include that header in your "controller" program.
Call the corresponding "program function" from the "controller" based on the input you read.