C++ Calculator with multiple input.

I tried to make my first C++ Calculator with Multiple inputs not just num1 and num2, but for example; "10 - 8 results to -18" I tried changing the 'result = 0;' to result; only but it doesn't get me where I want. Do I need to mess up with the whole code or create new ways to like store multiple numbers?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
  #include<iostream>
using namespace std;
int main (){
    int numberOfitems;
    double lc=1, number, choice, result = 0;
    char operation;
    cout << "You should only use (1) Operation all the way. Ex: (1+1+1+1).\nEnter number of items: ";
    cin >> numberOfitems;
    while (lc<=numberOfitems){
    cout << "Enter a number: ";
    cin >> number;
    if(lc < numberOfitems){
    cout <<"Operations +,-,* or /--: ";
    cin>>operation;
    }
    switch(operation) {
    case '+': {
    result=result+number;  //do stuff +
    } break;
    case '-': {
    result=result-number;//do stuff -
    } break;
    default: {
    cout << "Invalid Operation\n";
    } break;
                      }
    lc++;
                             }
    cout<<"____________"<<"\n Total answer is = "<<result<<endl;
}
what exactly did you type in?
seems like you would type
2 //number of numbers
10 //number
+ //first operation
//result = result+10 (0+10 = 10)
8 //
- //operation
result = 10-8 = 2

right?
for THAT to work, you have to remove this line:
//if(lc < numberOfitems)
so it was almost correct. but the comment "You should only use (1) Operation all the way." is not right; and it can't be right with this logic, you MUST allow different operations to code it this way as per the example input I gave.
Last edited on
ohhhh, so the logic ain't that right on point really. maybe I can use arrays for this? or is there anyway I can tweak the code to make it right?
its almost there so a tweak seems appropriate.
if you don't like the change I made, you need to find a way to 'seed' it. If you re-read what I said, you will see that the problem you were having is that result is not set to the first number input. you can do something kind of ugly but simple here:
if(lc == 1) result = number else (do what you were doing)
this is logically the same as adding the first number to result (which is what I did).

you can also do something fancy; if you took a page from reverse polish calculators and used stacks and queues to process the input it would work (with a fair amount of surgery and rewriting). That is a wee bit overkill given that you can get from where you are to where you want to be with a statement or two. But most advanced calculators will use some sort of heavy parsing of the input, so if you plan to build something like a full blown scientific calculator, you may want to rethink the approach.
Last edited on
Topic archived. No new replies allowed.