How to Take Operator as Input in C++?
Last Updated :
09 Feb, 2024
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++
#include <iostream>
using namespace std;
int main()
{
double num1, num2;
char op;
cout << "Enter the first number: " ;
cin >> num1;
cout << "Enter the second number: " ;
cin >> num2;
cout << "Enter the arithmetic operator (+, -, *, /): " ;
cin >> op;
double result;
switch (op) {
case '+' :
result = num1 + num2;
break ;
case '-' :
result = num1 - num2;
break ;
case '*' :
result = num1 * num2;
break ;
case '/' :
if (num2 != 0) {
result = num1 / num2;
}
else {
cout << "Error: Division by zero." << endl;
return 1;
}
break ;
default :
cout << "Error: Invalid operator." << endl;
return 1;
}
cout << "Result: " << result << endl;
return 0;
}
|
Output
Enter the first number: 8
Enter the second number: 2
Enter the arithmetic operator (+, -, *, /): /
Result: 4
Share your thoughts in the comments
Please Login to comment...