Well, I've just started learning C++ yesterday, and it's the first language I've ever learned.
I'm following some tutorials online, and I was messing around to try and create a simple calculator. However, I've hit two dead ends. Well, here's the source code first:
Code:
#include <iostream>
using namespace std;
//This is for adding x and y.
int addition(int x, int y) {
return x + y;
}
//This is for multiplying x and y.
int multiplication(int x, int y) {
return x * y;
}
//This is for dividing x and y.
int division(int x, int y) {
return x / y;
}
//This is for subtracting x and y.
int subtraction(int x, int y) {
return x - y;
}
//This is the main interface for the calculator.
int main() {
//The below 3 lines define the two numbers that will be entered by the user and the operation (addition, subtraction, etc).
int x;
int y;
char z;
cout << "Welcome to KK's calculator. Press any key to continue..." <<endl;
cin.get();
while (true) {
cout << "Input your first number: " << endl;
cin >> x;
cin.ignore();
cout << "Input your operation (+, -, *, /): " << endl;
cin >> z;
cin.ignore();
cout << "Input your second number and press Enter to get your solution: " << endl;
cin >> y;
cin.ignore();
/*if (y != 0) {
} else {
cout<< "Invalid operation. 0 cannot be the divisor." << endl;
}*/
if (z == '+') {
cout << "Answer: " << addition(x,y) << endl << endl;
} else if (z == '-') {
cout << "Answer: " << subtraction(x,y) << endl << endl;
} else if (z == '*') {
cout << "Answer: " << multiplication(x,y) << endl << endl;
} else if (z == '/') {
cout << "Answer: " << division(x,y) << endl;
} else {
cout << "Invalid operation. Please try again." << endl << endl;
}
}
cin.get();
return 0;
}
The first problem is that I want to prevent my program from going into an infinite loop if someone accidentally inputs a letter instead of a number.
The second is, I want to make sure you can't divide by 0, otherwise an error comes up.
I've tried to solve the 0 problem (it's in comments atm), but there's still a problem with it. It pops up my error message, but the program continues, and it breaks the application.
I would appreciate any tips and help. Suggestions to improve any existing code are welcome as well