Hi everyone! Im new here to the forums so im gonna give this a try.
Im taking an intro class to c++ and although ive been doing pretty well im stuck on a small issue.
Right now I am working on "creating a calculator". Here is a small piece of my code:
#include <iostream>
#include <math.h>
using namespace std;
int main()
{
double a,b,c;
char i;
cout << "This program is intended to be used as a calculator\n"
<< "Please enter: \n (1) the value of the first number\n (2) the symbol of the desired operation \n (3) and finally the second number\n"
case 'cos':
cin >> b;
c = a+b;
cout << "cos("<<b<<") = "<<c<<endl;
break;
default:
break;
}
system("pause");
return 0;
}
As you probably already noticed, I am using the switch/case structure with i as the index. The problem is I am using it as a char so it only stores one character but I need it to store more than one e.g. 'cos'. I also tried declaring i as: char i[5]; but when i do this it says switch quantity is not an integer.
Can comeone explain (in simplest words) how i can make 'i' longer than one letter AND make it work as a switch index?
What you are looking for are 'strings' ie; string i instead of char i. And a header #include <string>
But then you have a problem, because as far as I am aware you cannot use a string with switch statements as the 'index!' I think you need to reconfigure the switch statement so that you can work around your problem. For example you could ask the user to select the maths symbol first, then in the switch statement have them enter the values. There are actually multiple ways to do it.
I also see you need a semi-colon ; after the cout statement.
Also you have c = a+b in both '+' and 'cos' calculations. Not sure if thats intended??
switch(static_cast<int>(c))
{
case 65:
cout<<"You entered an A"; // example
break;
.
. //process all the characters
.
.
default:
//display an error message if user entered a wrong value
}
To me it looks like Bacos 001 is just starting out in c++. In my opinion enums and static casts should probably left till later. A simple switch and or if statements are all thats needed for a calculator.
Thank you guys for your input. Yes, like alphabravo said, I am barely starting out with c++. And I guess i have no choice but to go back and rewrite my code using if and else if. *sigh* I hate those. I personally think switch and case are cleaner a easier but alas it seems those dont work.
Once again thank you all
-B