Is there a way to write a program in such a way as to allow the user to type in the equation themselves? Similar to a graphing calculator. Example the user could type in 9*4 and press enter to receive the answer 36.
int num1; //This could be a double or float if you are dealing with decimals
charoperator; //The data type char can hold symbols, like +. -, *, /
int num2; //the second number, could also be a float/double
// Optional prompt for user to enter in equation
cin>>num1>>operator>>num2 //Equation is entered in
// ... And so on for all of the possible operators (/, *, etc)
You could also use this for functions (i.e. num1^num2 = pow(num1, num2))
It's more usual practice to read the whole string in and then split it up (tokenize it). To start with, this makes error handling easier. Then you can deal a bigger range of formatting styles (e.g. 1 + 2 versus 1+2). And it's easier to deal wth more complicated expressions, like 1 - 2 + 3 - 4 + 5 + 6
It's not too difficult to deal with arithmatic, including brackets, in this way. After reading the string in, you have to walk it char by char to find the numbers and operators are.
Handling just + and - is pretty easy.
You check each char in turn and if you find a digit, add it to a number string (which starts of empty).
- if it's anything else, add the existing number string to your list of tokens and clear the string.
- - if it's a space, ignore it
- - if it's an operator, add it to your list of tokens.
Anything else in the string is an error and you should abort.
Once you've finished tokenizing, calculate the results.
Adding multiplication and division, and brackets, is that bit harder (involves stacks).