I have started learning C++ recently and am currently working my way through various tutorials and books.
Most recently the object of interest was a very basic calculating program, running from the win prompt.
I understand the code and the program runs perfectly fine. However, I had the idea to try and add a little gimmick to the program. As you might already guess, that didn't work the way I expected. Actually, it didn't work at all.
The basic idea of the original program is, asking the user to input two numbers and then asking again to choose between adding, subtracting, multiplying and dividing the numbers, then displaying the result.
With the intent to increase my understanding of C++ and explore the code system a bit on my own I was wondering if it was possible to get the program to react to the result it puts out in the end.
My idea was to add a literature reference at the end if the output result equals 42, i.e. Don't Panic! or The answer to the great question or something like that. Would that be possible? And if so, what would I need to do?
The original code for the program is as follows:
#include <iostream>
int main()
{
using namespace std;
float num1;
float num2;
char op;
float ans;
cout << "Please enter a number: ";
cin >> num1;
cout << "Please enter another number: ";
cin >> num2;
cout << "Press A to add the two numbers." << endl;
cout << "Press S to subtract the two numbers." << endl;
cout << "Press M to multiply the two numbers." << endl;
cout << "Press D to divide the two numbers." << endl;
cin >> op;
if (op == 65)
ans = num1 + num2;
if (op == 83)
ans = num1 - num2;
if (op == 77)
ans = num1 * num2;
if (op == 68)
ans = num1 / num2;
cout << "The answer is " << ans << endl;
cin.clear();
cin.ignore(255, '\n');
cin.get();
return 0;
}
Like I said, this runs just like it should.
I tried to add my "Easter egg" by inserting an integer 'x' and declaring it being '42'. I then followed to insert the code that if 'ans' equals 'x' 'cout' should display my extra statement 'Don't Panic!'.
Like already mentioned, this didn't work. The compiler seems to have processed everything accordingly, no errors were reported, but the extra simply got left out.
Can somebody help me understand why that happens and help me fix it?
I'm hoping that I will be able to understand the code and programming in C++ a little better when venturing off the path given by the books and trying some new/other things that are not set in the curriculum.
Appreciate your help and would like to thank you in advance.