-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
  • 38,538
  • 10
  • 94
  • 140
Lynob
  • 4,483
  • 12
  • 55
  • 109
  • 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
  • 8,530
  • 6
  • 31
  • 61
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
  • 34,991
  • 6
  • 57
  • 84
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
  • 541
  • 1
  • 9
  • 21
0

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

Community
  • 1
  • 1
Aditya Sehgal
  • 2,799
  • 2
  • 26
  • 36