C++: Building a mulitfunctional calculator - c++

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...

Related

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

Basic Console Calculator (Storing a string in a variable) C++

I'm trying to create a basic console calculator in C++. I'm having a bit of trouble storing a string in a variable from a cin command.
Here is the program for some clarification:
#include <iostream>
using namespace std;
int main()
{
string type_cal;
cout << "Please enter the type of calculation you would like to use: \n";
cout << "1. Addition \n";
cout << "2. Subtraction \n";
cout << "3. Multiplication \n";
cout << "4. Division \n \n";
cin >> type_cal;
if (type_cal = "Addition" or "1")
{
int a;
int b;
int sum;
cout << "Please enter a number to add: \n";
cin >> a;
cout << "Please enter another number: \n";
cin >> b;
sum = a + b;
cout << "The sum of those numbers is: " << sum << endl;
return 0;
}
}
Currently I am in the addition phase since I recently ran into this problem. Quick answers would be appreciated, thank you!
if(type_cal = "Addition" or "1") simply does not make sense.
if(type_cal == "Addition" || type_cal == "1") {
}
Ok I found the problem, or is actually used as || in c++ (thanks aerkenemesis), and = is not the same as == which means equal to (another thanks to Lorehed). Program is working fine now.
For those who are curious, here is the new and revised version of my simple calculator:
#include <iostream>
using namespace std;
float addition();
float subtraction();
float multiplication();
float division();
int main()
{
string type_cal;
cout << "Please enter the type of calculation you would like to use: \n";
cout << "1. Addition " << endl;
cout << "2. Subtraction " << endl;
cout << "3. Multiplication " << endl;
cout << "4. Division" << endl << endl;
cin >> type_cal;
if(type_cal == "Addition")
{
addition();
}
if(type_cal == "Subtraction")
{
subtraction();
}
if(type_cal == "Multiplication")
{
multiplication();
}
if(type_cal == "Division")
{
division();
}
return 0;
}
float addition()
{
float a;
float b;
float sum;
cout << "Please enter a number to add: " << endl;
cin >> a;
cout << "Please enter another number: " << endl;;
cin >> b;
sum = a + b;
cout << "The sum of those numbers is: " << sum << endl;
}
float subtraction()
{
float c;
float d;
float difference;
cout << "Please enter a number to subtract: \n";
cin >> c;
cout << "Please enter another number: \n";
cin >> d;
difference = c - d;
cout << "The difference of those numbers is " << difference << endl;
}
float multiplication()
{
float e;
float f;
float product;
cout << "Please enter a number to multiply: \n";
cin >> e;
cout << "Please enter another number: \n";
cin >> f;
product = e * f;
cout << "The product of those numbers is " << product << endl;
}
float division()
{
float g;
float h;
float quotient;
cout << "Please enter a number to divide: \n";
cin >> g;
cout << "Please enter another number: \n";
cin >> h;
quotient = g / h;
cout << "The quotient of those numbers is " << quotient << endl;
}

C++ First program - Calculator

Hello I just started learning C++ and Im trying to make a calculator, right now having a fue problems that I simply dont know how to fix in C++.
#include <iostream>
using namespace std;
int main() {
int a, b, c, d;
cout << "1. Saskaitiissana(+)" << endl;
cout << "2. atnnemssana(-)" << endl;
cout << "3. daliissana(/)" << endl;
cout << "4. reizinaassana(*)" << endl;
cin >> d;
switch(d){
case 1 :
cout << "ievadiet a un b lai saskaitiitu(+)" << endl;
cin >> a;
cin >> b;
c = a + b;
cout << "The sum of number 1 and number 2 is " << c << "\n" <<endl;
break;
case 2 :
cout << "ievadiet a un b lai atnnemtu(-)" << endl;
cin >> a;
cin >> b;
c = a - b;
cout << c << endl;
break;
case 3 :
cout << "ievadiet a un b lai reizinaatu(*)" << endl;
cin >> a;
cin >> b;
c = a * b;
cout << c << endl;
break;
case 4 :
cout << "ievadiet a un b lai dal'itu(/)" << endl;
cin >> a;
cin >> b;
if(b==0)
{
cout<<"Nulle neder! start over."<<endl;
}
c = a/b;
cout << c << endl;
break;
}
return 0;
}
The things I still have to do.
Find the most easy way for the program to use numbers only. Also when I type in a number it can not be "empty space".
Also how can I make the case after it finish and gives you the result, go back to the begining of start menu? and if I want to exit a program I press esc or 5?
Also with the exit option I was thinking of useing do while "5" is pressed, can that work in c++?
Right now Im most interested on how to check program to use numbers only and have no empty space when adding numbers.
Thank you for your time :)
For ignoring non-numeric input you can this piece of code:
std::cin >> d;
while(std::cin.fail())
{
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(),'\n');
std::cout << "Bad entry. Enter a NUMBER: ";
std::cin >> d;
}
or in C-style:
while(scanf("%i",&d)!=1)
{
fseek(stdin,0,SEEK_END);
}
You can also put your whole bunch of code in a while statement to re-run the calculator after one operation.
Taking into account the safe input:
//----------------------------------------------------------------------------
#include <iostream>
using namespace std;
//----------------------------------------------------------------------------
void SafeDouble (double &d)
{
while (!(cin >> d))
{ cin.clear();
while (cin.get() != '\n');
cout << "\tIncorrect. Try again\n\t";
}
cin.sync();
}
//----------------------------------------------------------------------------
int main()
{
cout << "The simpliest calculator\n";
double a = 0.,b = 0.;
cout << "\na = ";
SafeDouble (a);
cout << "b = ";
SafeDouble (b);
cout << "\nEnter operation sign: +, -, * or /\n";
char op;
cin >> op;
cin.sync();
switch (op)
{
case '+': cout << a << " + " << b << " = " << a + b;
break;
case '-': cout << a << " - " << b << " = " << a - b;
break;
case '*': cout << a << " - " << b << " = " << a * b;
break;
case '/': if (b == 0.0)
cout << "Division by zero";
else
cout << a << " / " << b << " = " << a / b;
break;
default: cout << "Incorrect operation sign";
}
cin.get();
return 0;
}
//-----------------------------------------------------------------------------

Why do my stream input operations get skipped over?

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.

Should I use goto statement here?

A fine gentleman told me that goto statements were bad, but I don't see how I can not use it here:
int main()
{
using namespace std;
int x;
int y;
int z;
int a;
int b;
Calc: //How can i get back here, without using goto?
{
cout << "To begin, type a number" << endl;
cin >> x;
cout << "Excellent!" << endl;
cout << "Now you need to type the second number" << endl;
cin >> y;
cout << "Excellent!" << endl;
cout << "Now, what do you want to do with these numbers?" << endl;
cout << "Alt. 1 +" << endl;
cout << "Alt. 2 -" << endl;
cout << "Alt. 3 *" << endl;
cout << "Alt. 4 /" << endl;
cin >> a;
if (a == 1) {
z = add(x, y);
}
if (a == 2) {
z = sub(x, y);
}
if (a == 3) {
z = mul(x, y);
}
if (a == 4) {
z = dis(x, y);
}
}
cout << "The answer to your math question is ";
cout << z << endl;
cout << "Do you want to enter another question?" << endl;
cout << "Type 1 for yes" << endl;
cout << "Type 0 for no" << endl;
cin >> b;
if (b == 1) {
goto Calc;
}
cout << "Happy trails!" << endl;
return 0;
}
It is a calculator, as you can see. Also, if you want, can you suggest a better way (If it exists) to let the user choose the operation (+ - * /). Header files are under control.
I apologize for a lot of cout statements.
Here is a cleaned-up and properly formatted version using a do/while loop for structure:
using namespace std;
int main()
{
int x, y, z, a, b;
do {
cout << "To begin, type a number" << endl;
cin >> x;
cout << "Excellent!" << endl;
cout << "Now you need to type the second number" << endl;
cin >> y;
cout << "Excellent!" << endl;
cout << "Now, what do you want to do with these numbers?" << endl;
cout << "Alt. 1 +" << endl;
cout << "Alt. 2 -" << endl;
cout << "Alt. 3 *" << endl;
cout << "Alt. 4 /" << endl;
cin >> a;
if (a == 1) {
z = add(x, y);
}
else if (a == 2) {
z = sub(x, y);
}
else if (a == 3) {
z = mul(x, y);
}
else if (a == 4) {
z = dis(x, y);
}
cout << "The answer to your math question is ";
cout << z << endl;
cout << "Do you want to enter another question?" << endl;
cout << "Type 1 for yes" << endl;
cout << "Type 0 for no" << endl;
cin >> b;
} while (b != 0);
cout << "Happy trails!" << endl;
return 0;
}
Erm , use a proper looping construct, while, for etc.
the "more generally accepted" approach in this case would be a do {...} while(b==1); but the compiled results would likely be identical.
goto makes it difficult to track where execution is coming from, and where it's going.
goto encourages spagetti-code, unless you restrict heavily where it is used (e.g. you could argue that you only use it for cleanup blocks, but such an argument makes no sense in the presence of RAII).
you are using a goto to simulate a loop. Why are you not writing a loop instead?
it's obscure and thus, makes your code less available to other people.
goto makes it more difficult to track objects lifetimes.
Short answer to actual question: No, you should not use goto in this code. There is no need for it.
The use of goto should be "when it makes the code clearer or safer". The typical example of "makes the code clearer" is when there several layers of nested loops, and some particular situation requires leaving all the nesting levels, and adding a "do we want to exit the loop" makes the code more complicated. An example of "making it safer" is if a function holds a lock, opens a file or something similar, and needs to return early - but you also need to close the file or release the lock, using "goto exit_now;" is safer than trying to remember what locks, files, etc are held and then doing return;.
This:
if (a == 1) {
z = add(x, y);
}
if (a == 2) {
z = sub(x, y);
}
if (a == 3) {
z = mul(x, y);
}
if (a == 4) {
z = dis(x, y);
}
is a classic case of you should use 'switch':
switch(a)
{
case 1:
z = add(x, y);
break;
case 2:
z = sub(x, y);
break;
....
}
Makes the code clearer - there is also no confusion about whether a changes value and maybe another if statement becomes viable.
You can easily avoid 'goto' in your code. Just divide it into functions:
using namespace std;
void question () {
cout << "To begin, type a number" << endl;
cin >> x;
// put rest of the code here
}
int main () {
int ask = 1;
while ( ask == 1 ) {
question();
cout << "Do you want to enter another question?" << endl;
cout << "Type 1 for yes" << endl;
cout << "Type 0 for no" << endl;
cin >> ask;
}
return 0;
}
Edit: as noted in the comments, using do-while would be actually an better option.
goto isn't automatically bad. Unreadable code is bad. Whenever you find yourself in need of some obscure programming construct like 'goto', that usually means that your code is either poorly written, or that your program design is flawed.
The solution is almost always more functions. For example:
bool run_program();
int prompt_user_begin();
int prompt_user_again();
int prompt_operation_type();
bool prompt_continue();
int main()
{
while(run_program())
{}
cout << "Happy trails!" << endl;
return 0;
}
bool run_program()
{
int first;
int second;
int operation_type;
int result;
first = prompt_user_begin();
cout << "Excellent!" << endl;
second = prompt_user_again();
cout << "Excellent!" << endl;
operation_type = prompt_operation_type();
switch(operation_type)
{
case 1: result = add(first, second); break;
case 2: result = sub(first, second); break;
case 3: result = mul(first, second); break;
case 4: result = div(first, second); break;
}
cout << "The answer to your math question is ";
cout << result << endl;
return prompt_continue();
}
int prompt_user_begin ()
{
int x;
cout << "To begin, type a number" << endl;
cin >> x;
return x;
}
int prompt_user_again ()
{
int x;
cout << "Now you need to type the second number" << endl;
cin >> x;
return x;
}
int prompt_operation_type ()
{
int x;
cout << "Now, what do you want to do with these numbers?" << endl;
cout << "Alt. 1 +" << endl;
cout << "Alt. 2 -" << endl;
cout << "Alt. 3 *" << endl;
cout << "Alt. 4 /" << endl;
cin >> x;
return x;
}
bool prompt_continue ()
{
int x;
cout << "Do you want to enter another question?" << endl;
cout << "Type 1 for yes" << endl;
cout << "Type 0 for no" << endl;
cin >> x;
return x==1;
}