Why do my stream input operations get skipped over? - c++

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.

Related

C++: Building a mulitfunctional calculator

I am trying to build a calculator in C++. I'm new to the program and have to do this for a school assignment, so sorry for my ignorance. English is also my second language so excuse me if I don't make much sense.
Let's say I have two integers A and B for which a user has to assign a value to either add, subtract, etc. How would I then be able add a third integer (let's say X) without all three showing up when I run the program? So instead of having to type a value for A, B, AND X, it only asks to type a value for X?
For example 4 + 5 = 9, but the calculator can also square numbers, so how do I get the option of a user just filling in 4 squared = 16, while still keeping the former code that lets me add and subtract two numbers?
Maybe seeing the code would help understand what I mean? Sorry if I'm confusing.
#include <iostream.h>
#include <conio.h>
int main ()
{
cout << "Calculator [v.1.0]" << endl;
cout << "(c) 2021 <Chayenne van der Erf>" << endl << endl;
cout << "Kies een bewerking en druk op Enter:" << endl;
cout << "1. Optellen 2. Aftrekken" << endl;
cout << "3. Vermenigvuldigen 4. Delen" <<endl;
cout << "5. Kwadraat 6. Worteltrekken" <<endl;
cout << "7. Reciproke 8. Logarithme" <<endl;
cout << "0. Exit" << endl << endl;
int Bewerking;
cout << "Bewerking: ";
cin >> Bewerking;
cout << "" << endl;
switch (Bewerking) {
case 1:
cout << "+";
break;
case 2:
cout << "-";
break;
case 3:
cout << "*";
break;
case 4:
cout << "/";
break;
default: "Invalid Number";
}
cout << "" << endl << endl;
double A, B;
cout << "Enter een waarde: ";
cin >> A;
cout << "Enter een waarde: ";
cin >> B;
int antwoord;
if (Bewerking == 1) {antwoord = A + B;}
else if (Bewerking == 2 ) {antwoord = A - B;}
else if (Bewerking == 3) {antwoord = A * B;}
else if (Bewerking == 4) {antwoord = A / B;}
cout << "" << endl;
cout << "= " << antwoord << endl;
getch();
return 0;
}
Make the variables, and the reading, conditional on the operation.
Example outline:
if (operation takes one input)
{
double x;
cin >> x;
Calculate result...
}
else if (operation takes two inputs)
{
double x, y;
cin >> x >> y;
Calculate result...
}
else if (operation takes three inputs)
{
double x, y, z;
cin >> x >> y >> z;
Calculate result...
}
Print result...

Creating a function to output a string when the input is negative or zero. First time doing user-defined functions

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;
}

How do i fix this error: undefined reference to `distance(float, float, float, float)'

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.

Arrays Lose Value Upon Return (Inventory/Menu Program) C++

So for the most part I understand what I did wrong, the issue is I don't know how to fix it.
Goal: This is a store management system that must include a menu and inventory management functions that can be manipulated. To do this I used arrays to add the store's items, their descriptions, and their quantities. All the arrays are partially filled to the third element and have a max value of ten elements.
Issue: When the program is run the first time it works and the user can see their inventory, description and quantity. However when they exit to the menu and come BACK to inventory, everything past the third element is cleared. This is due to the declarations initializing the arrays past the third element to 0. How do I fix this to guarantee the user has their inventory saved and can view it upon return?
#include <iostream>
#include <vector>
#include <fstream>
#include <string>
#include <cmath>
#include <cstdlib>
using namespace std;
//declarations
int mainMenu(); //done
void inventoryMgmt();
void addInv(); //working on
void invView(string x[], int sizeofArray, string y[], int secondArray, int z[], int thirdArray);
void editor(string x[], int sizeofArray, string y[], int secondArray, int z[], int thirdArray);
void customerReciept(); //done
void calculatePrice(); //done
void exit(); //done
const double massTax = 0.0625;
//main
int main() {
int choice;
bool repeat = true;
while (repeat = true) {
choice = mainMenu();
switch (choice) {
case 1:
customerReciept();
break;
case 2:
inventoryMgmt();
break;
//case 3:
//itemSearcher();
//break;
case 4:
exit();
repeat = false;
break;
}
}
return 0;
}
//main menu function ***done
int mainMenu() {
cout << "\n\n\t\t\t\t Welcome to the Massasoit Store Management System " << endl;
cout << "\t\t\t\t ________________________________________________ \n\n";
cout << "\t\t\t\t\t Main Menu: " << endl;
cout << "\t\t\t\t\t\t 1. Customer Reciept" << endl;
cout << "\t\t\t\t\t\t 2. Inventory Management" << endl;
cout << "\t\t\t\t\t\t 3. Item Search" << endl;
cout << "\t\t\t\t\t\t 4. Exit" << endl << endl;
int choice;
cout << "\t\t\t\t\t\t Where do you need to go?: ";
cin >> choice;
while (choice < 1 || choice > 4) {
cout << "\t\t\t\t\t Incorrect Selection Please Select Again: ";
cin >> choice;
}
return choice;
}
//customer reciept function **done
void customerReciept() {
cout << "\n\n\t\t\t\t Welcome to the Massasoit Store: Customer Reciept " << endl;
cout << "\t\t\t\t ________________________________________________ \n\n";
cout << "\t\t\t\t\t Receipt Menu: " << endl;
cout << "\t\t\t\t\t\t 1. Calculate Receipt" << endl;
cout << "\t\t\t\t\t\t 2. Return to Main" << endl;
int recieptChoice;
cout << "\t\t\t\t\t\t Where do you need to go?: ";
cin >> recieptChoice;
while (recieptChoice < 1 || recieptChoice > 2) {
cout << "Invalid Selection Please Choose Again: ";
cin >> recieptChoice;
}
if (recieptChoice == 1) {
calculatePrice();
}
}
void calculatePrice() {
double cost;
double taxAmount;
int numOfItems;
double finalCost = 0;
char tax;
int i;
cout << "\n\n\t\t\t\t Welcome to the Massasoit Store: Customer Reciept " << endl;
cout << "\t\t\t\t ________________________________________________ \n\n";
cout << "How many items were purchased?: ";
cin >> numOfItems;
for (i = 0; i < numOfItems; i++) {
cout << "What did item " << i + 1 << " cost? $";
cin >> cost;
cout << "Is this item taxable? (y/n):";
cin >> tax;
if (tax == 'y' || tax == 'Y') {
taxAmount = (cost * massTax);
cost = taxAmount + cost;
finalCost = cost + finalCost;
}
else {
finalCost = cost + finalCost;
}
}
cout.setf(ios::fixed);
cout.setf(ios::showpoint);
cout.precision(2);
cout << "This customer's total is $" << finalCost << endl;
}
void inventoryMgmt() {
int invChoice;
cout << "\n\n\t\t\t\t\t Welcome to Inventory Management " << endl;
cout << "\t\t\t\t ______________________________________________ \n\n";
cout << "\t\t\t\t\t Inventory Settings: " << endl;
cout << "\t\t\t\t\t\t 1. Add/View & Edit/Delete Inventory" << endl;
cout << "\t\t\t\t\t\t 2. Return to Main" << endl;
cout << "\t\t\t\t\t\t Where do you need to go?: ";
cin >> invChoice;
cout << endl << endl;
while (invChoice < 1 || invChoice > 2) {
cout << "Invalid Selection Please Choose Again: ";
cin >> invChoice;
}
if (invChoice == 1) {
addInv();
}
if (invChoice == 2) {
//edit/delete();
}
}
void addInv() {
//so when this is called, everything is initialized to 0 which makes it wipe the memory
//when the user comes back to it from the menu.
const int description = 20; //this allows a short description for each item
const int counter = 10; //slots of inventory allowed
int quantity[10] = {10, 15, 45};
string itemArray[counter] = { "Hot Drinks", "Cold Drinks", "Books"};
string descriptionArray[description] = { "Coffee, Tea etc", "Water, juice, etc", "Texts, notebook, etc"};
char addChoice;
int destination;
cout << "\t\t\t\t\t\t 1. Add/View" << endl;
cout << "\t\t\t\t\t\t 2. Edit/Delete" << endl;
cout << "\t\t\t\t\t\t 3. Exit to Main" << endl;
cout << "\t\t\t\t\t\t Where would you like to go?: " << endl;
cin >> destination;
while (destination < 1 || destination > 3) {
cout << "Invalid Selection, Please Select Again: ";
cin >> destination;
}
if (destination == 1) {
cout << "Would you like to add an item? (y/n): ";
cin >> addChoice;
int i = 3; //these two are initialized to three to ensure that the store
int ii = 3; //will always have hot drinks, cold drinks and books as options
while (addChoice == 'y' && i < counter) {
cout << "What would you like to add?: ";
cin >> itemArray[i];
cout << "You have added \"" << itemArray[i] << "\" to the inventory\n";
cout << "Please Provide a Brief Description: ";
cin.ignore();
getline(cin, descriptionArray[ii]);
cout << "You've described \"" << itemArray[i] << "\" as \"" << descriptionArray[i] << "\"" << endl;
cout << "What is the quantity of " << itemArray[i] << " in stock?";
cin >> quantity[i];
cout << "Would you like to add another item?";
cin >> addChoice;
i++;
ii++;
if (i > counter) {
cout << "**INVENTORY LIMIT REACHED*** ";
}
}
invView(itemArray, 10, descriptionArray, 10, quantity, 10); //working on this. //so use this for view, edit, and delete.
}
}
void invView(string x[], int sizeofArray, string y[], int secondArray, int z[], int thirdArray) { //add quantity
int i = 0;
int ii = 0;
int iii = 0;
cout << "Your inventory consists of: ";
while (i < sizeofArray && x[i] != "" && ii < secondArray && y[i] != "" && iii < thirdArray) {
cout << x[i] << " - " << y[i] << " | Quantity: " << z[i] << endl;
i++;
ii++;
}
}
void editor(string x[], int sizeofArray, string y[], int secondArray, int z[], int thirdArray) {
cout << "Which item would you like to edit?";
}
void exit() {
cout << "\n\n\t\t\t\t Welcome to the Massasoit Store Management System " << endl;
cout << "\t\t\t\t ________________________________________________ \n\n";
cout << "\t\t\t\t Thank you for using the Massasoit Store Management System" << endl;
exit(1);
}
I included the entire code in case it was needed. The issues are centered around the inventoryMgmt() and addInv() functions.
Thanks in advance for any help!
In theaddInv() all the arrays are local. Once that function is done executing, all local variables are freed up thus resulting in your deletion. Try place them outside your addInv() function:
int main(){
int quantity[10] = {10, 15, 45};
string itemArray[counter] = { "..."};
string descriptionArray[description] = { "..."};
void addInv() {...}
}

else if executes executes automatically before asking for user input

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.