I am new to c++ programming, I would like to create a program to find area, volume of shapes I used switch case to select shapes and used else if inside switch for selecting area or volume but it executes only one switch statement.
#include <iostream>
#include<cmath>
#define _USE_MATH_DEFINES
#include<math.h>
#define PI 3.14159
using namespace std;
int main() {
double radius;
double square;
double qube;
double quboid;
double cylinder;
double sphere;
double a;
double length;
double breadth;
double height;
double width;
char userchoice1;
char userchoice;
cout << "Select any shape by typing the no correctly\n";
cout << "1-square\n";
cout << "2-Cube\n";
cout << "3-Cuboid\n";
cout << "4-Circle\n";
cout << "5-Sphere\n";
cout << "6-rectangle\n";
cout << "Select any shape by typing the no correctly\n";
cin >> userchoice;
switch (userchoice) {
case '1':
cout << "3-area\n";
cout << "4-perimeter\n";
if (userchoice = 3) {
cout << "Enter side a\n";
cin >> a;
cout << "Area of square is " << a * a << "sq.units" << endl;
} else if (userchoice = 4) {
cout << "Enter side\n";
cin >> a;
cout << "Perimeter of square is " << 4 * a << "sq.units" << endl;
}
break;
case '2':
cout << "1-area\n";
cout << "2-volume\n";
if (userchoice = 1) {
cout << "Enter side a\n";
cin >> a;
cout << "Area of cube is " << 6 * a * a << "sq.units" << endl;
} else if (userchoice = 2) {
cout << "Enter side a\n";
cin >> a;
cout << "Volume of cube is " << a * a * a << "cu.units" << endl;
}
break;
case '3':
cout << "Enter length, breadth, height\n";
cin >> breadth;
cin >> length;
cin >> height;
cout << "Area of cuboid is " << (length * breadth * height) << "sq.units" << endl;
break;
case '4':
cout << "1-circumference\n";
cout << "2-Area\n";
if (userchoice = 1) {
cout << "Enter the radius of circle\n";
cin >> radius;
cout << "Circumference of circle is " << 2 * PI * radius << endl;
} else if (userchoice = 2) {
cout << "Enter the radius of circle\n";
cin >> radius;
cout << "Area of circle is " << PI * radius * radius << "sq.units" << endl;
}
break;
case '5':
cout << "1-Area\n";
cout << "2-volume\n";
if (userchoice = 1) {
cout << "Enter the radius of Sphere\n";
cin >> radius;
cout << "Area of Sphere is " << 4 * PI * radius * radius << "sq.units" << endl;
} else if (userchoice = 2) {
cout << "Enter the radius of Sphere\n";
cin >> radius;
cout << "Volume of Sphere is " << (4 / 3 * PI * radius * radius) << "cu.units" << endl;
}
break;
case '6':
cout << "1-Area\n";
cout << "2-perimeter\n";
if (userchoice = 1) {
cout << "Enter length width\n";
cin >> length;
cin >> width;
cout << "Area of rectangle: " << length * width << "sq.units" << endl;
} else if (userchoice = 2) {
cout << "Enter side\n";
cin >> a;
cout << "Perimeter of rectangle is " << 4 * a << "sq.units" << endl;
}
break;
}
}
switch statements can only execute through one case. It can "fall through" if you don't use breaks though. If you mean that it's not executing any of the if statements in the switch statement, it's because you're using the "assignment" operator (=) in the condition. You should be using the "is equal to" operator (==) instead.
So your if statements should be something like this:
if (userchoice == 1) {
// ... do something ...
}
else if (userchoice == 2) {
// ... do something else ...
}
Even if you do that, you have another problem that I notice. You're using the same variable in the condition of the if and switch statements. Doing it that way will make it impossible to execute some routes. You should use separate variables for both and prompt the user for both. Either that, or reassign "userchoice" to be used in the if statements.
Also, you're declaring "userchoice" as a char. If you declare it as a char, you should test for a char in the conditions. If not, declare it as an int.
Related
I was trying out c++ function and recursion but it seems I'm having quite a problem in the variable. I left a comment below where the error usually is found. I dont know where is my problem hoping someone can help me point it out. Thank you! Is it the Variables? or the whole program is flawed? ;-;
#include <conio.h>
#include <iomanip>
#include <iostream>
using namespace std;
float Volume_Cube(float s);
float Volume_Sphere(float r);
float Volume_Rectangle(float w, float h, float l);
int main() {
char opt;
float V;
do {
do {
cout << "*******************************************************" << endl;
cout << " Mark Justine H. Monterde" << endl;
cout << " Volume of Shapes" << endl;
cout << "*******************************************************" << endl;
cout << " [C]-cube" << endl;
cout << " [S]-Sphere" << endl;
cout << " [R]-Rectangular Parallelepiped" << endl;
cout << " [X]-Exit" << endl;
cout << "*******************************************************" << endl;
cin >> opt;
switch (opt) {
case 'C':
case 'c':
float side;
cout << "Enter side: " << endl;
cin >> side;
V = Volume_Cube(side);
cout << fixed << setprecision(2);
cout << "The Volume of the cube is " << V << endl;
break;
case 'S':
case 's':
float radius;
cout << "Enter Radius: " << endl;
cin >> radius;
V = Volume_Sphere(radius);
cout << fixed << setprecision(2);
cout << "The Volume of the Sphere is " << V << endl;
break;
case 'R':
case 'r':
float width, height, length;
cout << "Enter Length: " << endl;
cin >> length;
cout << "Enter Width: " << endl;
cin >> width;
cout << "Enter Height: " << endl;
cin >> height;
V = Volume_Rectangle(width, height, length);
cout << fixed << setprecision(2);
cout << "The Volume of the Rectangular Parallelepiped is " << V
<< endl;
break;
case 'X':
case 'x':
return 0;
break;
default:
cout << "Denied...." << endl;
}
cout << "\nPress any key to continue...\n";
_getch();
} while (opt != 'X ' && opt != 'x');
cout << "\nThank you for using the program \n";
return 0;
}
float Volume_Cube(float s) { //<-mostly my errors comes from here//
float VOLUME;
VOLUME = s * s * s;
return VOLUME;
}
float Volume_Sphere(float r) {
float VOLUME;
const float PI = 3.14;
VOLUME = ((4 / 3) * PI * r * r * r);
return VOLUME;
}
float Volume_Rectangle(float w, float h, float l) {
float VOLUME;
VOLUME = w * h * l;
return VOLUME;
}
}
Here is your code again, with the compiler errors and warnings fixed. It now behaves as [mostly] expected. I placed comments where I made changes and marked them with the text CHANGE: . Your logic was sound, the syntax was just sloppy.
One area that I have not made changes to is how you exit. You immediately return, which means that your code below (thank you message, etc.) is never executed. Making those changes hinders this answer (in my opinion), so I'll leave it pointed out for you to work on. Suggestions are in the comments to this answer as of this writing.
// #include <conio.h> // CHANGE: Removed; outdated and not standard
#include <iomanip>
#include <iostream>
using namespace std;
float Volume_Cube(float s);
float Volume_Sphere(float r);
float Volume_Rectangle(float w, float h, float l);
int main() {
char opt;
float V;
// do { // CHANGE: Removed
do {
cout << "*******************************************************" << endl;
cout << " Mark Justine H. Monterde" << endl;
cout << " Volume of Shapes" << endl;
cout << "*******************************************************" << endl;
cout << " [C]-cube" << endl;
cout << " [S]-Sphere" << endl;
cout << " [R]-Rectangular Parallelepiped" << endl;
cout << " [X]-Exit" << endl;
cout << "*******************************************************" << endl;
cin >> opt;
switch (opt) {
case 'C':
case 'c':
float side;
cout << "Enter side: " << endl;
cin >> side;
V = Volume_Cube(side);
cout << fixed << setprecision(2);
cout << "The Volume of the cube is " << V << endl;
break;
case 'S':
case 's':
float radius;
cout << "Enter Radius: " << endl;
cin >> radius;
V = Volume_Sphere(radius);
cout << fixed << setprecision(2);
cout << "The Volume of the Sphere is " << V << endl;
break;
case 'R':
case 'r':
float width, height, length;
cout << "Enter Length: " << endl;
cin >> length;
cout << "Enter Width: " << endl;
cin >> width;
cout << "Enter Height: " << endl;
cin >> height;
V = Volume_Rectangle(width, height, length);
cout << fixed << setprecision(2);
cout << "The Volume of the Rectangular Parallelepiped is " << V << endl;
break;
case 'X':
case 'x':
return 0;
break;
default:
cout << "Denied...." << endl;
}
cout << "\nPress any key to continue...\n";
// _getch(); // CHANGE: Removed; Not found
} while (opt != 'X' && opt != 'x'); // CHANGE: Extra space after X removed
cout << "\nThank you for using the program \n";
return 0;
}
float Volume_Cube(float s) { //<-mostly my errors comes from here//
float VOLUME;
VOLUME = s * s * s;
return VOLUME;
}
float Volume_Sphere(float r) {
float VOLUME;
const float PI = 3.14;
VOLUME = ((4.0 / 3.0) * PI * r * r * r); // CHANGE: integers to doubles
return VOLUME;
}
float Volume_Rectangle(float w, float h, float l) {
float VOLUME;
VOLUME = w * h * l;
return VOLUME;
}
// } // CHANGE: Removed
Proper formatting, and enabling compiler warnings caught all of these without the need for any actual investigations.
Proper styling can be achieved in many ways. In my case, my editor (VS Code) performs some styling automatically like auto-indents. But I also back that up with a tool, clang-format.
For warnings, -Wall -Wextra should be considered a minimum. Some people might recommend a couple others to go with these, but I consider this a good minimum.
You are declearing functions inside main, that is a function itself, and this is illegal, try declearing them outside.
So I am not really sure what to do here, I have gone back over my code multiple times and it all seems to be right but I keep getting the error code
Stubblefield9.cpp:74: undefined reference to `distance(float, float, float, float)'
collect2.exe: error: ld returned 1 exit status
Here is my code if anyone can help me.
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;
int main()
{
const float pi=3.14;
int choice;
char again;
do
{
cout << " IHCC Computer Science Registration Menu\n";
cout << " ======================================\n";
cout << " 1. The Volume of a Cone\n";
cout << " 2. The Volume of a Sphere\n";
cout << " 3. The Area of an Octagon\n";
cout << " 4. The Destance between two Points\n";
cout << " ======================================\n";
cout << " Enter your selection: ";
cin >> choice;
switch (choice)
{
case 1:
float coneRadius,coneHeight,coneVolume;
cout<<"Enter the Radius of the cone:";
cin>>coneRadius;
cout<<"\nEnther the Height of the Cone: ";
cin>>coneHeight;
coneVolume=pi*coneRadius*coneRadius*coneHeight/3;
cout<<"\nThe Volume of a Cone with Radius ("<< coneRadius << ") and Height (" << coneHeight << setprecision(2) << fixed << ") is " << coneVolume;
break;
case 2:
float sphereRadius,sphereVolume;
cout << "Please insert the Radius: ";
cin >>sphereRadius;
sphereVolume = (4/3)*(pi)*(sphereRadius*sphereRadius*sphereRadius);
cout<<"Volume with radius "<< setprecision(1) << fixed << sphereRadius << setprecision(2) << fixed << " is "<<sphereVolume;
break;
case 3:
float octagonSide, octagonArea;
cout << "Input side length: ";
cin >> octagonSide;
octagonArea =(2 * (1 + sqrt(2)) * octagonSide * octagonSide);
cout << "\nThe area of the octagon with side length (" << octagonSide << setprecision(2) << fixed << ") is "<< octagonArea;
break;
case 4:
float x, y, a, b, answer;
float distance(float x, float y, float a, float b);
cout << "Enter the points for the coordinates";
cout << endl;
cout << "Point x for first coordinates: ";
cin >> x;
cout << endl;
cout << endl;
cout << "Point y for first coordinate: ";
cin >> y;
cout << endl;
cout << endl;
cout << "Point x for the second coordinate: ";
cin >> a;
cout << endl;
cout << endl;
cout << "Point y for the second coordinate: ";
cin >> b;
cout << endl;
cout << endl;
answer = distance(x, y, a, b);
cout << "The answer is " << answer;
break;
default:
cout << "Not a Valid Choice. \n";
cout << "Choose again.\n";
cin >> choice;
break ;
}
cout << "\n\n Would you like to do it again(y or n)";
cin >> again;
} while( again == 'y' || again == 'Y' );
return 0;
}
You get that error because you try to call a function distance() that is declared in your code by
float distance(float x, float y, float a, float b);
but not defined.
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.