A simple calculator program in C++ can be a wonderful way to understand the basics of programming, such as input/output operations, conditional statements, and basic arithmetic operations. This program highlights the utilization of the switch...case
statement, which is suitable for scenarios where a variable is checked against multiple values.
In this article, you will learn how to build a simple calculator in C++ that performs addition, subtraction, multiplication, and division. Discover how to efficiently manage user input and output, handle basic arithmetic operations, and implement control flow using the switch...case
statement.
Include necessary headers and declare the main function.
Define variables to store user inputs for the numbers and the operation choice.
#include<iostream>
using namespace std;
int main() {
double num1, num2;
char operation;
cout << "Enter first number: ";
cin >> num1;
cout << "Enter second number: ";
cin >> num2;
cout << "Enter operation (+, -, *, /): ";
cin >> operation;
This block of code sets up the basic input mechanisms and variables for storing numbers and the chosen operation.
switch
Setup the switch
statement to handle different operations based on user input.
Define cases for addition, subtraction, multiplication, and division.
Display the result to the user.
switch(operation) {
case '+':
cout << "Result: " << num1 + num2 << endl;
break;
case '-':
cout << "Result: " << num1 - num2 << endl;
break;
case '*':
cout << "Result: " << num1 * num2 << endl;
break;
case '/':
// Check division by zero scenario
if(num2 != 0.0)
cout << "Result: " << num1 / num2 << endl;
else
cout << "Cannot divide by zero" << endl;
break;
default:
cout << "Invalid operation" << endl;
break;
}
return 0;
}
This code block evaluates the user input and performs the requested arithmetic operation. Note the check for division by zero to avoid runtime errors.
Add error handling for invalid inputs.
Consider using functions to separate logic and make code cleaner.
Add looping to handle multiple calculations without restarting the program.
bool isValidInput = cin.fail();
if(isValidInput) {
cout << "Invalid input detected!" << endl;
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
This snippet improves error handling by checking if the input operation failed, clearing the error flag, and ignoring incorrect input.
Creating a simple calculator using C++ and the switch...case
approach provides a solid foundation in handling basic user inputs, performing arithmetic operations, and applying conditional statements efficiently. Adjust and expand this basic calculator to include more operations or functionalities as you become more comfortable with C++ syntax and logic handling. By doing so, you ensure that your journey into the world of programming is both educational and practical.