[Error] expected unqualified-id before 'switch'

Hey im new on this forum and tried to code a little calculater but the compiler gives me the error "expected unqualified-id before 'switch'"

The code:
int zahl2 = zahl1;
int operation;

int main() {

cout << "Geben sie eine Zahl ein!" << endl;
cin >> zahl1;
cout << "Geben sie erneut eine Zahl ein!" << endl;
cin >> zahl2;
cout << "Mit was wollen sie rechnen +, -, *, /" << endl;
cin >> operation;
}

switch(operation) {
case + :
cout << zahl1 + zahl2 << endl;
break;
case - :
cout << zahl1 - zahl1 << endl;
break;
case * :
cout << zahl1 * zahl2 << endl;
break;
case / :
cout << zahl1 / zahl2 << endl;
break;
}

(error in line 16)

BeefYolo
Last edited on
Firstly, your switch is outside of main so won't do anything even if it compiles. Secondly, you have to put quotes around something for it to be interpreted as a char by the compiler (i.e. '-' not - and '+' not +).
Here, I had to edit the code quite a bit, because there were multiple errors.

Like shadowmouse said, your "switch" was outside of any function, so it doesn't have any effect. Also int zahl2 = zahl1; I don't know what you tried to do here. I think you tried to declare two integers? The way to do that is: int zahl1, zahl2;.

And yes, in your case statements you must put the operations (+, -, *, /) in single quotes so they can be interpreted as a char.

Also it's better to use double or float in this situation, since if you input (3 / 4) the result will be 0.

Here is the code:

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
#include <iostream>
using namespace std;

int main() 
{
	double zahl1, zahl2;
	char operation;
	
	cout << "Geben sie eine Zahl ein!" << endl;
	cin >> zahl1;
	cout << "Geben sie erneut eine Zahl ein!" << endl;
	cin >> zahl2;
	cout << "Mit was wollen sie rechnen +, -, *, /" << endl;
	cin >> operation;

	switch(operation) 
	{
		case '+' :
		cout << zahl1 + zahl2 << endl; break;
		case '-' :
		cout << zahl1 - zahl1 << endl; break;
		case '*' :
		cout << zahl1 * zahl2 << endl; break;
		case '/' :
		cout << zahl1 / zahl2 << endl;break;
	}
}
Topic archived. No new replies allowed.