You can get the input and store it in std::string
and then convert it to anything that is needed (like double
, char
, etc).
Also, it's better to use a switch
statement instead of that if-else if-else chain.
With a bit of refactoring (and keeping things as simple as possible):
#include <iostream>
#include <string>
#include <stdexcept>
struct OperationData
{
double num1;
double num2;
double result;
char opp;
};
double get_input_double( )
{
std::string num_str;
std::getline( std::cin, num_str );
return std::stod( num_str );
}
void printResult( const OperationData& operation_data )
{
std::cout << operation_data.num1 << ' ' << operation_data.opp
<< ' ' << operation_data.num2 << " = " << operation_data.result << '\n';
}
int main( )
{
while ( true )
{
std::cout << "Enter e or E to exit the program, or any other character to continue: ";
std::string isExiting { " " };
std::getline( std::cin, isExiting );
if ( isExiting[0] == 'e' || isExiting[0] == 'E' ) { break; }
std::cout << "Enter the first number\n";
double num1 { };
try
{
num1 = get_input_double( );
}
catch ( const std::invalid_argument& ) { std::cout << "Invalid argument\n"; continue; }
catch ( const std::out_of_range& ) { std::cout << "Entered value out of range\n"; continue; }
std::cout << "Enter the operator\n";
std::string opp_str { " " };
std::getline( std::cin, opp_str );
const char opp { opp_str[0] };
std::cout << "Enter the second number\n";
double num2 { };
try
{
num2 = get_input_double( );
}
catch ( const std::invalid_argument& ) { std::cout << "Invalid argument\n"; continue; }
catch ( const std::out_of_range& ) { std::cout << "Entered value out of range\n"; continue; }
switch ( opp )
{
case '+' :
printResult( { num1, num2, num1 + num2, opp } );
break;
case '-' :
printResult( { num1, num2, num1 - num2, opp } );
break;
case '*' :
printResult( { num1, num2, num1 * num2, opp } );
break;
case '/' :
printResult( { num1, num2, num1 / num2, opp } );
break;
default :
std::cout << "INVALID OPERATOR\n";
}
}
}
Sample input/output:
Enter e or E to exit the program, or any other character to continue:
Enter the first number
45.5
Enter the operator
/
Enter the second number
3
45.5 / 3 = 15.1667
Enter e or E to exit the program, or any other character to continue: E
Note: If the input is not convertible to double
, std::stod
will throw a std::invalid_argument
or a std::out_of_range
exception and in the above code there are try-catch blocks to handle the exceptions. An appropriate message will be displayed and the program will jump to the beginning of the loop to start the process from the first step whenever an exception is thrown.