Operators are symbols that specify some kind of operation. In C++, we sometimes need to take operators as user input mainly to perform mathematical operations. In this article, we will learn how to take operators as user input in C++.
Operators as Input in C++
To take operators (like +,-,*,/ etc) as user input, we can use a char datatype to read the operator as a character using cin and then validate whether the entered operator is valid or not using a switch or conditional statements.
C++ Program to Take Operator as Input
The below example demonstrates how we can take the operator as user input, validate it, and perform mathematical calculations.
// C++ program to take operator as input #include <iostream> using namespace std;
int main()
{ // Declaring variables to store two numbers and the
// operator
double num1, num2;
char op;
// Get the first number from the user
cout << "Enter the first number: " ;
cin >> num1;
// Get the second number from the user
cout << "Enter the second number: " ;
cin >> num2;
// Get the arithmetic operator from the user
cout << "Enter the arithmetic operator (+, -, *, /): " ;
cin >> op;
// Declare a variable to store the result of the
// operation
double result;
// Use a switch statement to perform the operation based
// on the operator
switch (op) {
case '+' :
result = num1 + num2;
break ;
case '-' :
result = num1 - num2;
break ;
case '*' :
result = num1 * num2;
break ;
case '/' :
// Check if the second number is not zero before
// performing division
if (num2 != 0) {
result = num1 / num2;
}
else {
cout << "Error: Division by zero." << endl;
return 1; // Return an error code
}
break ;
default :
cout << "Error: Invalid operator." << endl;
return 1; // Return an error code
}
// Display the result of the operation
cout << "Result: " << result << endl;
return 0;
} |
Output
Enter the first number: 8
Enter the second number: 2
Enter the arithmetic operator (+, -, *, /): /
Result: 4