-5

my friend wrote a c++ code, it's not working, and he came to me for help. the problem is that i don't know c++ :) i'm more interested in python and i don't want to learn c++ anytime soon, so i come here for help :) here's the code

#include<iostream>

using namespace std;

int main (){
    char a ;
    cin >> a ;
    switch (a) {
    case '+' :
        int x , y , result ;

        cout << "Enter A number >> " ;
        cin >> x ;
        cout << endl ;

        cout << "Enter A number >> " ;
        cin >> y ;
        cout << endl ;

        result = x+y ;

        cout << "The Answer Is >> " << result << endl ;
        break ;
    case '-' :
        int x , y , result ;

        cout << "Enter A number >> " ;
        cin >> x ;
        cout << endl ;

        cout << "Enter A number >> " ;
        cin >> y ;
        cout << endl ;

        result= x-y ;

        cout << "The Answer Is >> " << result << endl ;
        break ;
    default :
        cout << "Please choose the right operaions !" << endl ;
    }
    return 0 ;
}
Mankarse
  • 39,818
  • 11
  • 97
  • 141
Lynob
  • 5,059
  • 15
  • 64
  • 114
  • 2
    Please indent your code, it is really hard work to read when it isn't. – Yacoby Nov 13 '11 at 12:13
  • 5
    "Not working" is not a good error description. State any compiler errors and/or any runtime outputs together with your expected outputs. – thiton Nov 13 '11 at 12:15

4 Answers4

2

You are defining int x, y, result for multiple times within one statement block. Merge the definitions and move to the top of the function, then it will compile. Like:

char a;
int x, y, result;
Ryan Li
  • 9,020
  • 7
  • 33
  • 62
1
 case '+' :
        int x , y , result ;

        cout << "Enter A number >> " ;
        cin >> x ;
        cout << endl ;

        cout << "Enter A number >> " ;
        cin >> y ;
        cout << endl ;

        result = x+y ;

        cout << "The Answer Is >> " << result << endl ;
        break ;

doesn't work but you can get it to compile by adding a scope:

 case '+' :
        {
           int x , y , result ;

           cout << "Enter A number >> " ;
           cin >> x ;
           cout << endl ;

           cout << "Enter A number >> " ;
           cin >> y ;
           cout << endl ;

           result = x+y ;

           cout << "The Answer Is >> " << result << endl ;
        }
        break ;

...

but code should be restructured since there is a lot of duplicate code.

AndersK
  • 35,813
  • 6
  • 60
  • 86
0

You declared int x,y and result of type int 2 times in the statement "switch". Declare them global variables or outside the switch statement(within main() function).

Kanghu
  • 561
  • 1
  • 10
  • 23
0

Defining variables inside the switch block does not work and here's why

Community
  • 1
  • 1
Aditya Sehgal
  • 2,867
  • 3
  • 27
  • 37