I'm doing a calculator program that I would like to be able to just take the whole problem someone needs solved (i.e. 5+6) instead of having to enter the numbers and operators separately. I would also like to know how you can search through a whole array of characters and see if any one them are an operator without having to look at each individual one. This is the code, which doesn't work(Say, if I enter 5+2 it comes out with 103). It's not my whole program but it's just a sample of what it will be doing.
1 2 3 4 5 6 7 8 9 10 11 12 13 14
#include <iostream>
usingnamespace std;
int main()
{
char problem[3];
cout << "Enter problem to solve: ";
cin >> problem;
if (problem[1] = '+')
{
cout << problem[0] + problem[2] << '\n';
}
system("PAUSE");
return 0;
}
P.S. I'm confused on how character arrays work because if I declare
char string[10] It can hold more than 10 characters?
This is why std::string exists for your variable-length-string needs.
For your program to work initially, you may want to consider using string::find to locate your operators, then use stoi on the portions of the string (string::substr) before and after that operator to get the actual integer values they represent. This is an overly simplified strategy that will break the moment you try to include more than one operator, but it should get you going. :)
As far as your initial attempt goes and why it doesn't work, you are adding the ASCII representations of your digits on line 10 and not the values those characters represent, which are much greater than 5 and 2, hence your strange result. The simplest way to convert them is to subtract '0' before doing the addition.