### How to make my calculator, calculate more than 2 numbers?

// I made this simple calculator and its working just fine. But it can calculate only 2 numbers at a time. I want it to calculate as many number as I desire. So how can I do that?

#include <iostream.h>
#include <conio.h>

void main()

{

int a,b;

char op;

cin>>a>>op>>b;

switch (op)

{

case '/':cout<<"="<<(a/b);break;

case '*':cout<<"="<<(a*b);break;

case '+':cout<<"="<<(a+b);break;

case '-':cout<<"="<<(a-b);break;

case '%':cout<<"="<<(a%b);break;

}

getch();

}
Last edited on
firstly, if you enter 6 '/' 4, what do you think the answer will be with your current code?

for more numbers you will have to store them and the operators in a vector or array then write something to iterate through this building up an answer as you go.
Last edited on
Input the first number, and then loop over inputting the operator and the second number, modifying the first number based on them, and display the result if the operator is =. Here is a quick example:
 ``123456789101112131415161718192021222324`` ``````#include // not iostream.h using namespace std; // use the standard namespace // #include // also non standard, see http://www.cplusplus.com/forum/beginner/1988/ // don't use void main, use int instead int main() { int a, b; char op = '\0'; cout << "Enter an expression, press '=' to finish: "; cin >> a; // while the user hasn't pressed = while (op != '=') { cin >> op >> b; switch(op) { case '/': a /= b; break; case '*': a *= b; break; //... case '=': cout << a << '\n'; break; } } return 0; } ``````

Of course, this doesn't process operator precedence, but I will leave that as a (very difficult) exercise to you. I recommend using something like Bison or boost::spirit, otherwise you will have great trouble.
Last edited on
You could have a vector holding all your numbers you want then iterate through the vector to do the calculations. You could use an array also but you'd have to predefine its size. Vector will allow you to increase its size based on your input.

closed account (iAk3T05o)
`int main()` not `void main()`
Topic archived. No new replies allowed.