Calculator H.E.L.P.

program crashes when i try to enter the first operation. any help is great. Here's the code:


#include <iostream>
using namespace std; // so we dont have to use std

int main () // start function
{
double num1; // first number
double num2; // second number
double answer; // answer
char op1; // first operation
char op2; // second operation
char quit; // quit option
char op;

do // start do loop
{
cout << " welcome to my calculator\n"; // welcom screen

cout << " enter first number\n"; // user enters first number

cin >> num1; // input users answer

cout << "enter an operation ( + - * or / ) \n";

cin >> op1;


do // second loop
{


switch (op) // start of switch
{

cout << "enter another number\n";
cin >> num2;

case '+' : (answer = num1 + num2);
cout << "total is "; cout << answer;
cout << "enter another operation ( + - * / or =) \n";
cin >> op2;
if (op2 != '=') (answer=num1);
break;

case '-' : (answer = num1 - num2);
cout << "total is "; cout << answer;
cout << "enter another operation ( + - * / or =) \n";
cin >> op2;
if (op2 == '=')
break;

case '*' : (answer = num1 * num2);
cout << "total is "; cout << answer;
cout << "enter another operation ( + - * / or =) \n";
cin >> op2;
if (op2 != '=') (answer=num1);
break;

case '/' : (answer = num1 / num2);
cout << "total is "; cout << answer;
cout << "enter another operation ( + - * / or =) \n";
cin >> op2;
if (op2 != '=') (answer=num1);
break;
}
} while (op2 != '=');

cout << "your answer is "; cout << answer; cout << endl;
cout << "Quit? (Y or N) ";
cin >> quit;

} while (quit != 'N');

return 0;
}
You are switching on op, but op is never initialized or set.
Have you even tried compling your code? Looks like you haven't.

Whats this??
if (op2 != '=') (answer=num1);
anonymouscoder6,

I believe this line is o.k., since op2 is supposed to be a char. The user could enter '=' at the command prompt. If all of the variables were initialized and/or set, I believe the code will compile and run as is.
CPPMATT,
I was not talking about the '=', I was referring to the statement after condition check. Isn't answer=num1 supposed to be in curly braces rather than ()?
anonymouscoder6,

No, this need not be in curly braces. An IF statement can execute without curly braces, just like this:

1
2
 if (num>x)
     num-=1;


Now the compiler doesn't care if we instead write:

1
2
if (num>x)
   (num-=1);


And since the compiler ignores white space, this is equivalent to:

if (num>x) (num-=1);


I agree that it is bad style and makes the code hard to read.
Last edited on
Topic archived. No new replies allowed.