I am having trouble with this programming assignment. I need to calculate the value of total resistance for a parallel and series circuit. I have the series circuit functioning, but my problem is that when I try to calculate the total resistance for parallel circuit, my return value is 1.#INF. Any suggestions to how I can fix this
// project.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
#include <math.h>
using namespace std;
void menu()
{
cout <<"\t\t\tLab 2 Menu Driven Algorithms" << endl;
cout <<"\t\t Calculating Parallel and Series Resistance" << endl;
cout <<"1)\tSeries" << endl;
cout <<"2)\tParallel" << endl;
cout <<"3)\tQuit" << endl;
}
int series(int& num, int& sum)
{
int answer;
num = 0;
sum = 0;
do
{
cout << "Enter Resistor " << num+1 << " value, 0 to calculate: ";
cin >> answer;
cout << endl;
sum = sum + answer;
num++;
}
while(answer != 0);
return sum;
}
double parallel (int& num, double& sum)
{
double answer;
num = 0;
sum = 0.0;
int counter = 0;
do
{
cout << "Enter Resistor " << num+1 << " value, 0 to calculate: ";
cin >> answer;
cout << endl;
counter++;
sum = (1/answer) + sum;
cout << sum << endl;
num++;
}
while(answer != 0);
return sum;
}
int main()
{
char choice;
int num = 0;
int sum = 0;
double sum2 = 0.0;
menu();
cout <<"\n\nPlease enter a value from the menu: ";
cin >> choice;
cout << endl;
while (choice != '3' && choice != 'q' && choice != 'Q')
{
switch(choice)
{
case '1': cout << "Calculating Series Resistance" << endl;
cout << "The series resistance for the " << num-1 << " resistors is: " << series(num, sum) << " Ohms\n";
system("pause");
break;
case '2': cout << "Calculating Parallel Resistance" << endl;
cout << "The parallel resistance for the " << num-1 << " resistors is: " << parallel(num, sum2) << " Ohms\n";
system("pause");
break;
default: break;
}
system("cls");
menu();
cout <<"\n\nPlease enter a value from the menu: ";
cin >> choice;
cout << endl;
}
system("pause");
return 0;
}
You probably want to rewrite the cycle inside the parallel() function this way, so that you will never process a value of 0 (which causes a division by zero in this case):
cout << "Enter Resistor " << num+1 << " value, 0 to calculate: ";
cin >> answer;
cout << endl;
while (answer != 0);
{
counter++; // NOTICE: This is never used for computation...
sum = (1/answer) + sum;
cout << sum << endl;
num++;
cout << "Enter Resistor " << num+1 << " value, 0 to calculate: ";
cin >> answer;
cout << endl;
}
The counter variable is never used for computation, so I guess you could get rid of it.
Also notice, that even the loop inside series() has a similar problem, although the fact that you never cause a division by zero doesn't make it visible.
Related
I just want to ask a question.
I am coding a system of linear equations in two variables using the 2-dimensional array. on the second equation, it is always multiplied with - so that it is easier to solve the x or y in equation 1.
how can you change the sign of the numbers in equation 2 if the ax+by= c is not the same?
I only know how to negate all the numbers in the second equation with the use of negative absolute value but I am facing difficulty if the user inputs on negative and positive numbers in equation 2.(-2x + 3y = -4).
Here is my code (it is not done since I am confused on how to change signs of an array independently because of the user input. I am just a beginner)
/*
Linear equation using elimination method
*/
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;
const int row = 2;
const int col = 3;
int list[row][col];
int list1[row][col];
int list2[row][col];
int rsize, y, x;
char operation;
int ir, ic;
int *ptr;
//function declaration
void equation1(int list[][col], int rsize);
//to display the value in 2D array plus linear equation
void Elimination(int list1[][col], int rsize);
//input the 2 values to elimate in eqn1 and eqn2
//then display the new equations that is already multiplied to the 2values
void final1(int list1[][col], int rsize,int Y);
//diplay the value of computed Y and the equation need to substitute the value of Y
//process and computes the value of X
//and finally, display the solution set of (x,y)
void final2(int list1[][col], int rsize,int X);
//diplay the value of computed X and the equation need to substitute the value of X
//process and computes the value of Y
//and finally, display the solution set of (x,y)
int deterY(int list2[3]); //computes the value of Y and returns the value of Y
int deterX(int list2[3]); //computes the value of X and returns the value of X
char choice(); //display the menu and returns the value of choice
int main() {
char opt, ulit, operation;
int equation;
opt = choice();
int solve_for_x, solve_for_y;
switch(opt) {
case '1': //two dimensional
do {
system("cls");
cout << "SYSTEMS OF LINEAR EQUATIONS:\n"
<< "Solving by addition or elimination\n";
//ADD CODE HERE
cout << "This program uses Addition or Elimination Method.\n"
<< "We begin by setting up and evaluating the three variables x, y and the constant.\n"
<< "For example,\n 5x + y = -14 \nshould be entered as 5 1 -14";
cout << "\n\nPress any key to continue....";
cin >> opt;
cin.ignore();
cin.get();
system("cls");
cout << "Again, 5x + y = -14 should be entered as 5 1 -14\n";
//ADD CODE HERE
equation1(list, row);
cin.ignore();
cout<<"\n\nPress any key to continue...." <<endl;
cin.get();
system("cls");
Elimination(list1, row);
cout << "\n\n\n";
cout << "What variable do you want to change: \n";
cout << "x or y\n";
cin >> operation;
switch(operation){
case 'x':
solve_for_x = deterX(list2[3]);
cout << solve_for_x <<endl;
break;
case 'y':
solve_for_y = deterY(list2[3]);
cout << solve_for_y << endl;
break;
}
//Call function Elimination here
//ADD CODE HERE
} while (toupper(ulit) == 'Y');
break;
case '2':
//ADD CODE HERE
break;
} //end switch
system("pause");
return 0;
} //end main
///////////////////////////////////////////////////////////
char choice() {
cout << "<<<<<<<MENU>>>>>>>" << endl;
cout <<"[1] Systems of Linear Equation"<<endl;
cout <<"[2] Quit" << endl;
cout <<"Enter your choice:" << endl;
char opt;
cin >> opt;
return opt;
}
///////////////////////////////////////////////////////////////
void equation1(int ist[][col], int rsize) {
cout << "Enter Equation 1:";
for(ir = 0; ir < row; ir++) {
for(ic = 0; ic < col; ic++) {
if(ir == 0 && ic >= 0) {
cin >> list[ir][ic];
}
if(ir == 1 && ic >= 0) {
cout << "Enter Equation 2:";
cin >> list[ir][ic];
}
}
}
} //end equation1
///////////////////////////////////////////////////////////
void Elimination(int list1[][col], int rsize) {
cout << "you have entered (using 2-dimensional array)" << endl;
for(ir = 0; ir < row; ir++) {
for(ic = 0; ic < col; ic++) {
cout < <setw(7) << list[ir][ic];
}
cout << endl;
}
cout << endl;
cout << "SOLVING SIMPLE EQUATIONS" << endl;
cout << setw(7) << list[0][0] << "x" << " + " <<list[0][1] << "y" << " = " << list[0][2] << endl;
cout << setw(7) << list[1][0] << "x" << " + " <<list[1][1] << "y" << " = " << list[1][2] << endl;
cout << "\n\n\n\n";
cout <<"_____________________________________________________ "<< endl;
cout << "Please enter the value to eliminate the variable" << endl;
cout << "for example... if you have:" <<endl;
cout << "2x + 3y = 10" << endl;
cout << "4x + 5y = 15" << endl;
cout << "if you want to eliminate the x.. you need to input -2" << endl;
cout << "(for 2x to become -4x in eqn.1) and 1 (to remain the value in eqn.2" << endl;
cout << "if you want to eliminate y.. you need to input -/+5 in eqn1 and +-3 in eqn.2" << endl;
cout << "enter the value for equation 1: 1 " << endl;
cout << "enter value for equation 2: -1 " << endl;
cout << "\n\n\n";
cout << "ELIMINATING EQUATIONS" << endl;
cout << setw(7) << list[0][0] <<"x" << " + " <<list[0][1] <<"y" << " = " << list[0][2] << endl;
cout << setw(7) << -abs(list[1][0])<<"x" << " + " << -abs(list[1][1]) <<"y" << " = " << -abs(list[1][2]) << endl;
cout <<"===================================================== "<< endl;
}
////////////////////////////////////////////////////
int deterY(int list2[3]){}
///////////////////////////////////////////////
int deterX(int list2[3]) {}
///////////////////////////////////////////////////////
void final1(int list1[][col], int rsize,int Y) {}
////////////////////////////////////////////////////////////////////////////
void final2(int list1[][col], int rsize,int X) {}
#include <iostream>
using namespace std;
int main()
{
int numint, sum, a, b, ctr;
cout << "Enter the number of intervals: ";
cin >> numint;
ctr = 0;
while (ctr != numint)
{
cout << "Enter the lower and upper bounds of the interval: ";
cin >> a;
cin >> b;
ctr++;
}
cout << "The sum of the " << numint << " intervals is: [" << a << "," << b << "]";
return 0;
}
I need to add the upper bounds of the interval (a) and lower bounds of the interval (b). This depends on the amt of intervals there are.
here:
cout << "The sum of the " << numint << " intervals is: [" << a << "," << b << ]";
you are not adding the values but instead just printing them
instead use some accumulator variable and do the math before printing it, like:
int main()
{
int numint,sum,a,b,ctr;
int result = 0;
cout << "Enter the number of intervals: ";
cin >> numint;
ctr=0;
while (ctr!=numint)
{
cout << "Enter the lower and upper bounds of the interval: ";
cin >> a;
cin >> b;
ctr++;
}
result = a + b ;
cout << "The sum of the " << numint << " is: " << result;
return 0;
}
As for what I understood from the question, you first need a int resultA=0 and another for b, and keep adding in the loop:
#include <iostream>
using namespace std;
int main()
{
int numint,sum,a,b,ctr;
int result = 0;
int resultA=0;
int resultB=0;
cout << "Enter the number of intervals: ";
cin >> numint;
ctr=0;
while (ctr!=numint)
{
cout << "Enter the lower and upper bounds of the interval: ";
cin >> a;
cin >> b;
resultA+=a;
resultB+=b;
ctr++;
}
result = resultA + resultB ;
cout << "The sum of the " << numint << " is: " << result;
return 0;
}
I think this is what you are looking for:
#include <iostream>
using namespace std;
int main() {
int numberOfIntervals;
int lowerBound;
int upperBound;
int counter;
int lowerBoundSum = 0;
int upperBoundSum = 0;
cout << "Enter the number of intervals: ";
cin >> numberOfIntervals;
counter = 0;
while (counter != numberOfIntervals) {
cout << "Enter the lower and upper bounds of interval "
<< counter << ": ";
cin >> lowerBound;
cin >> upperBound;
lowerBoundSum += lowerBound;
upperBoundSum += upperBound;
counter++;
}
cout << "The sum of the lower bounds is " << lowerBoundSum
<< endl;
cout << "The sum of the upper bounds is " << upperBoundSum
<< endl;
return 0;
}
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() {...}
}
Hey so the code I made should be working to calculate the passer rating for quarterbacks in the NFL. The program, however, returns a value of 0 for almost anything, unless I put ridiculously large numbers, in which case it gives 100. What's wrong with it?
#include <iostream>
using namespace std;
int main()
{
int PassCompletions;
cout << "Enter pass completions" << endl;
cin >> PassCompletions;
int PassAttempts;
cout << "Enter pass attempts" << endl;
cin >> PassAttempts;
int TotalPassY;
cout << "Enter total yards" << endl;
cin >> TotalPassY;
int Touch;
cout << "Enter touchdowns" << endl;
cin >> Touch;
int Int;
cout << "Enter interceptions" << endl;
cin >> Int;
int C = (PassCompletions/PassAttempts-0.30)*5;
int Y = (TotalPassY/PassAttempts-3)*0.25;
int T = (Touch/PassAttempts)*20;
int I = 2.375 - (Int/PassAttempts*25);
if (C<0){
C=0;
}
if (Y<0){
Y=0;
}
if (T<0){
T=0;
}
if (I<0){
I=0;
}
if (C>2.375){
C=2.375;
}
if (Y>2.375){
Y=2.375;
}
if (T>2.375){
T=2.375;
}
if (I>2.375){
I=2.375;
}
int PasserRating = (C+Y+T+I)/6*100;
if (PasserRating <= 85){
cout << "Rating " << PasserRating << ", this is poor" << endl;
}
if (PasserRating > 85 && PasserRating < 90){
cout << "Rating " << PasserRating << ", this is mediocre" << endl;
}
if (PasserRating > 90 && PasserRating < 95){
cout << "Rating " << PasserRating << ", this is good" << endl;
}
if (PasserRating > 95){
cout << "Rating " << PasserRating << ", this is great" << endl;
}
You need use data type which is suitable to store fractional value. For this purpose use float instead of int for these statements:
float C = (PassCompletions/PassAttempts-0.30)*5;
float Y = (TotalPassY/PassAttempts-3)*0.25;
float T = (Touch/PassAttempts)*20;
float I = 2.375 - (Int/PassAttempts*25);
The variable type int is only used to store whole numbers, eg 1,2,3...
Any expression with a decimal will be truncated and rounded down. Since you are doing a lot of calculations with floating point numbers, eg. 2.375, I would suggest you changing your int's to float's
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.