Switch Default Statement
Apr 13, 2015 at 8:38am UTC
(First post! :] ) Hello. Im trying to make a basic calculator with four operators only. I want the program to state an error if the user doesnt enter one of the four operators. I assume this would be achieved using the 'default' statement but its not working for me. Any help would be appreciated. thank you
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
#include <iostream>
#include <conio.h>
using namespace std;
int main ()
{
float numb1, numb2;
char opr;
float answer;
char response;
while ( response != 'n' )
{
cout << "\nEnter first number, operator, second number: " ;
cin >> numb1 >> opr >> numb2;
cout << "\nAnswer is: " << answer << endl;
switch (opr)
{
case '+' : answer = numb1 + numb2; break ;
case '-' : answer = numb1 - numb2; break ;
case '*' : answer = numb1 * numb2; break ;
case '/' : answer = numb1 / numb2; break ;
default : cout << "Invalid operator!" ; break ;
} // end switch
cout << "\nDo another? (y/n): " << response;
response = getche();
cout << endl;
} // end while
return 0;
}
Apr 13, 2015 at 10:40am UTC
Move the
cout << "\nAnswer is: " << answer << endl;
inside the case statments
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
case '+' : answer = numb1 + numb2;
cout << "\nAnswer is: " << answer << endl;
break ;
case '-' : answer = numb1 - numb2;
cout << "\nAnswer is: " << answer << endl;
break ;
case '*' : answer = numb1 * numb2;
cout << "\nAnswer is: " << answer << endl;
break ;
case '/' : answer = numb1 / numb2;
cout << "\nAnswer is: " << answer << endl;
break ;
default : cout << "Invalid operator!" ; break ;
Apr 13, 2015 at 12:45pm UTC
or you could move your cout << "\nAnswer is: " << answer << endl;
at the end...
Topic archived. No new replies allowed.