Hello everyone, i have started to learn C++ with the help of the book called Jumping into C++. Now i have hit the first wall, i am not sure what i am doing wrong, or i just lack knowledge to make it work.
My task says:
Make your calculator program perform computations in a seperate function for each type of computation.
My only problem is, when i am about to add a value for x or y and i add NOT a number, so for example a letter like f. Then my while loop becomes an infinite loop with the infinite spam of else statement.
I am stuck at this for 2 days now, and i do not really wanna move forward more in the book until i do not finish all the Practice Problems.
Code:
#include <iostream>
#include <string>
using namespace std;
int add(int x, int y)
{
return x+y;
}
int subtract(int x, int y)
{
return x-y;
}
int divide(int x, int y)
{
return x/y;
}
int multiply(int x, int y)
{
return x*y;
}
int main()
{
int x;
int y;
string symbol;
cout<< "Enter your first number: ";
cin>>x;
cout<< "Enter your second number: ";
cin>>y;
cout<< "Enter your argument: ";
cin>>symbol;
while(1)
{
if(symbol=="+")
{
cout<< "Your number is: ";
cout<< add(x,y);
break;
}
else if(symbol=="-")
{
cout<< "Your number is: ";
cout<< subtract(x,y);
break;
}
else if(symbol=="/")
{
if(y==0)
{
cout<< "Divide cannot be done with 0, please try again.\n";
cout<< "Enter your second number again: ";
cin>>y;
}
cout<< "Your number is: ";
cout<< divide(x,y);
break;
}
else if(symbol=="*")
{
cout<< "Your number is: ";
cout<< multiply(x,y);
break;
}
else
{
cout<< "Invalid character(s). Please try again.\n";
cout<< "Enter your first number: ";
cin>>x;
cout<< "Enter your second number: ";
cin>>y;
cout<< "Enter your argument: ";
cin>>symbol;
}
}
}