I am programming a sum and subtraction only calculator in c++. I'm using 2 void functions, one for the user interface whereas the user can choose wether to use the sum or subtraction functions (or exit the program as well). The other one is made up of 3 conditionals, the first 2 to the algebraic operation the calculator has to do in order to deliver the result of the arithmetical operation. The third one is for when the user didn't choose a valid option, and redirects the user to where it started.
The problem here is that the second conditional if being ignored. For instance, if I input "2" or "2.", the program says outputs "Invalid choice", as if the third conditional was met, but it is not for sure. How can I solve this? Here's the code:
#include <iostream>
#include <thread>
using namespace std;
float userInterfaceChoice;
float num1;
float num2;
void conditionals();
void userInterface()
{
cout<<"CALCULATOR"<<endl
<<""<<endl
<<"Please choose an option"<<endl
<<"1. Sum"<<endl
<<"2. Subtraction"<<endl
<<"3. Exit"<<endl;
cin>>userInterfaceChoice;
this_thread::sleep_for(1s);
conditionals();
}
void conditionals()
{
// Sum
if(userInterfaceChoice==("1"||"1."))
{
// Input of numbers
cout<<""<<endl
<<"SUM"<<endl
<<"Enter the first number"<<endl;
cin >>num1;
cout<<""<<endl
<<"Enter the second number"<<endl;
cin >>num2;
// Operation & Output
cout<<"The sum equals "<<num1+num2<<endl;
// Wait 2 seconds, then come back to the GUI
this_thread::sleep_for(2s);
userInterface();
}
// Subtracion
else if(userInterfaceChoice==("2"||"2."))
{
// Numbers input
cout<<""<<endl
<<"SUM"<<endl
<<"Enter the first number"<<endl;
cin >>num1;
cout<<""<<endl
<<"Enter the second number"<<endl;
cin >>num2;
// Operation & Output
cout<<"The subtraction equals"<<num1-num2<<endl;
// Wait 2 seconds, come back to the GUI
this_thread::sleep_for(2s);
userInterface();
}
//Invalid choice
else if(userInterfaceChoice!=("1"&&"1."&&"2"&&"2."))
{
cout<<""<<endl
<<"Invalid choice"<<endl;
// Wait 2 seconds, come back to the GUI
this_thread::sleep_for(2s);
userInterface();
}
}
// Execute the void functions
int main()
{
userInterface();
conditionals();
}
I tried to solve this problem by deleting the third conditional, but the program exits with exit code 0, which meeans that still the conditional is't met or is straightaway ignored.