calculator that uses switch and private class

hello, I'm studying c++ and I'm trying to make a calculator that uses a switch statement and public/private classes. The code I've written seems logical to me but it just doesn't work, can someone please help me?



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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
#include <iostream>
#include <windows.h>

using namespace std;
class crab
{

    public:
    crab(){

            cin >> x;
            cin >> input;
            cin >> y;

    }
    void setCalc (int input){

             switch (input){
            case "x":
            x*y;
            break;
            case "+":
            x+y;
            break;
            case "-":
            x-y;

            default:
           system("pause");
            }

            z = input;









   }

    int getCalc (){
           return z;
   }

    private:
           int x,y,z;



};



int main()
{
    crab ob;
    ob.setCalc (input);
    cout << ob.getCalc();

    return 0;
}
anyone?
There are quite a few problems with the code right now. Will try and explain some of them.

In your switch statement you are checking the variable 'input' for the various things it can be such as + / * etc. However you passed the input variable in as an int (which can only hold whole numbers), so it is not able to hold those values. You will need to use a char variable and check each one using singular quotations (as that's standard for char variables, eg '+').

Your second problem is related to function scope. On line 60 you pass input into your setCalc function, however main has never seen this variable before (as it is not mentioned anywhere in the main function). The same problem is seen in your class constructor, input is listed there but there is no variable definition of it anywhere so the compiler will not be able to fill it. You will need to create a private variable in your class called input to use it in all of the class functions, there is no need to pass anything into any of the functions.

Make sure every case in your switch statement has a break at the end of it so that it breaks out of the loop completely as soon as a match is found (I even recommend one for default although isn't really needed).

The final problem is you are setting z equal to input on line 32, however that is meant to be the symbol the user enters, not the answer...while the cases in your switch statement aren't doing anything as they aren't being assigned to any variable. Delete your code on line 32 and set each of the case values equal to z instead, so it actually prints out the answer. z = x*y;

Let me know if any of that needs explaining further, I also recommend you look up some pages on function scope and some general knowledge on classes to help.
thank u ill try and fix everything
Topic archived. No new replies allowed.