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;
}
//-----------------------------------------------------------------------------
Related
How do you provide a condition in the if statement, if the variable is an integer data type then it will be displayed, and if the variable is any other data type then something else will be displayed?
#include <iostream>
#include <stdlib.h>
#include <windows.h>
#include <conio.h>
using namespace std;
int main() {
char pilih,pilih2;
int p, l, a, t, r,ulang = 4;
float luas1, luas2, luas3, keliling1, keliling2, keliling3, phi = 3.14;
while (ulang > 0) {
pilihUlang:
cout << "Pilih jenis bangun datar berikut :\n 1. Persegi panjang\n 2. Segitiga sama sisi\n 3. Lingkaran" << endl;
cout << "Masukan pilihan anda [1/2/3] : ";
cin >> pilih;
system("cls");
switch (pilih) {
case '1':
system("color 07");
cout << "Luas Dan Keliling Persegi Panjang" << endl;
cout << "Masukan Panjang = ";
cin >> p;
if (?) { // <-- here
cout << "Masukan Lebar = ";
cin >> l;
system("cls");
cout << "Luas dan keliling Persegi Panjang dengan panjang " << p << " dan lebar " << l << ", yaitu :" << endl;
luas1 = p * l;
keliling1 = 2 * (p + l);
cout << "Luas = " << luas1 << endl;
cout << "Keliling = " << keliling1 << endl;
cout << "Sisa bisa memilih ulang " << ulang - 1 << " kali." << endl;
break;
}
else {
//...
}
From the istream::operator>> man page:
If extraction fails (e.g. if a letter was entered where a digit is
expected), zero is written to value and failbit is set.
So, your function could test the cin.good() method to see if the >> operation was successful, like this:
cin >> p;
if (cin.good()) {
cout << "The integer you typed was " << p << endl;
} else {
cout << "Hey, that wasn't an integer!" << endl;
}
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...
I am making a calculator in C++ and it works fine except when I divide by zero. So I have an if statement saying to give the message "Error Divide buy zero" when a number is divide by zero. However the program still crashes.
Here is my code
#include <iostream>
using namespace std;
int main()
{
int a, b, d, s;
d == a/b
cout << "Enter first number\n";
cin >> a;
cout << "Enter second number\n";
cin >> b;
cout << "Select the operation you want\n";
cout << "1.Addition\n";
cout << "2.Subtraction\n";
cout << "3.Multiplication\n";
cout << "4.Division\n";
cin >> s;
switch (s)
{
case 1: cout << "Addition Selected\n"; a+b << endl; break;
case 2: cout << "Subtraction Selected\n"; a-b << endl; break;
case 3: cout << "Addition Selected\n"; a*b << endl; break;
case 4:
if (b==0)
{
cout << "Error Divide by Zero"<< endl;
}
else
{
cout << d << endl;
}
break;
default: cout << "Invalid Selection" << endl;
}
return 0;
}
On a secondary note when I select an operation it doesn't say that it was selected.
Your code has a lot of syntax errors.
Perhaps this can help you. This smartly avoids divide by zero and prints error message also.
#include <iostream>
using namespace std;
int main() {
int n1, n2, ans;
char op;
cin >> n1 >> op >> n2;
switch (op) {
case '+':
ans = n1 + n2;
break;
case '-':
ans = n1 - n2;
break;
case '*':
ans = n1 * n2;
break;
case '/':
if (n2) {
ans = n1 / n2;
break;
}
default:
cerr << "Invalid Input" << endl;
return 1;
}
cout << ans;
return 0;
}
See http://ideone.com/wa8QJG demo.
Your line
d == a/b;
Needs to be
d = a/b;
and it needs to move within the "else" clause. Otherwise the division by 0 error occurs before the print explaining the error.
You are also missing a print for the divide case and should add that.
There are many typos/syntax errors in your code.
Here is a working solution close to your code:
int main()
{
int a, b, d, s;
cout << "Enter first number\n";
cin >> a;
cout << "Enter second number\n";
cin >> b;
cout << "Select the operation you want\n";
cout << "1.Addition\n";
cout << "2.Subtraction\n";
cout << "3.Multiplication\n";
cout << "4.Division\n";
cin >> s;
switch( s )
{
case 1:
cout << "Addition Selected\n" << a + b << endl;
break;
case 2:
cout << "Subtraction Selected\n" << a - b << endl;
break;
case 3:
cout << "Multiplication Selected\n" << a * b << endl;
break;
case 4:
if( b == 0 )
{
cout << "Error Divide by Zero" << endl;
}
else
{
d = a / b;
cout << d << endl;
}
break;
default:
cout << "Invalid Selection" << endl;
}
return 0;
}
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.
#include <iostream>
#include <string>
using namespace std;
//void multiply(int b);
int main()
{
float total = 0;
float b = 0;
cout << "Enter number: " << endl;
cin >> b;
char TorD;
cout << "Would you like to times (*), divide (/), add (+) or minus (-) this number?" << endl;
cin >> TorD;
switch (TorD)
case '*' :
{
int c=0;
cout << "by how many?" << endl;
cin >> c;
total = b * c;
cout << b << " * " << c << " = " << total << endl;
}
break;
case '/' :
{
int c=0;
cout << "by how many?" << endl;
cin >> c;
total = b / c;
cout << b << " / " << c << " = " << total << endl;
}
break;
case '+' :
{
int c=0;
cout << "by how many?" << endl;
cin >> c;
total = b + c;
cout << b << " + " << c << " = " << total << endl;
}
break;
case '-' :
{
int c=0;
cout << "by how many?" << endl;
cin >> c;
total = b - c;
cout << b << " - " << c << " = " << total << endl;
}
break;
default:
cout << "You did not correctly enter /, *, +, or - !!" << endl;
//multiply(b);
system("pause");
return 0;
}
You're missing the open brace after the switch (TorD), so the 'break' is outside any statement to break from (i.e. a break has to be inside a loop or switch so it has something to break out of). The switch statement should look like:
switch (TorD) {
case '*': {
// ...
}
break;
case '/': {
// ...
}
break;
// ...and so on.
}
You need braces for your switch:
switch (...)
{ // your forgot this
...
} // and this
You forgot the curly braces around case statements after switch.