Considering the error statement, you definitely need to use the above mentioned solution:
But beyond this, your code will still fail. The only problem with your code, really, is that you declared the variable "operation" as a char. When you do this, you're getting only the character representation of '1', '2', '3', or '4' as input from the user, and therefore when the program is instructed which operation to perform in your "if" statements, it's essentially using junk data. There are two ways to go about this, the first one requiring fewer changes to your code:
Just change the declaration of "operation" to:
...and all will be right with the world again.
Also, in the code you included, you're using a cout with ">>", when it should be "<<" and you spelled "endl" wrong in one spot. Just typos, no biggie.
The following code compiled and ran in Dev-C++ with your desired result:
- #include <iostream>
-
-
using std::cout;
-
using std::cin;
-
using std::endl;
-
-
int num1 = 0;
-
int num2 = 0;
-
int answer = 0;
-
int operation;
-
-
int main()
-
{
-
cout << "Enter first number: ";
-
cin >> num1;
-
cout << "Enter 1 (add) or 2 (subtract) or 3 (multiply) or 4 (divide): ";
-
cin >> operation;
-
cout << operation;
-
cout << "Enter second number: ";
-
cin >> num2;
-
-
if (operation == 1)
-
{
-
answer = num1 + num2;
-
cout << "Sum: " << answer << endl;
-
}
-
else
-
if (operation == 2)
-
{
-
answer = num1 - num2;
-
cout << "Difference: " << answer << endl;
-
}
-
else
-
if (operation == 3)
-
{
-
answer = num1 * num2;
-
cout << "Product: " << answer << endl;
-
}
-
else
-
if (operation == 4)
-
{
-
answer = num1 / num2;
-
cout << "Quotient: " << answer << endl;
-
} //end if
-
-
system ("pause");
-
return 0;
-
} //end of main function
Just to be thorough, here is the second way to go about this: if you were to keep the declaration as:
...then, when you use your "if" statements, they have to look like this:
This way, the "if" statement compares the char input to another char. So the moral of the story is, all you need is to make sure similar data types are being compared in the "if" statement (or any control statement for that matter).
One more thing, while I'm at it... it is widely accepted that you should not use the SYSTEM("PAUSE") command because, depending on your system, instability could result and this is not portable code. I use Windows XP and code with Dev-C++, and I find that the easiest way to keep the console window open is to use:
... before the return statement, which gets input from the current input stream. In your code you should use it twice, as such:
This is because the first time you call the command, it will "get" the user's last input because that input stream still exists. The second cin.get() call asks for input, but nothing is currently in the stream, so the program holds the window open until it has some kind of input to read. Therefore, you can press enter, the program will read the empty input, and the window closes.