Case statement not within loop or switch

September 18, 2010 at 09:52:21
Specs: Windows 7 Professional, 32-bit, Debian 5.0 Lenny 32-bit, Ubuntu 10.04 LTS triple boot, 2.0 GHz, 3.00 GB RAM
This code will not compile. It is source code for a calculator I am trying to make in c++.
When I compile it, I am getting the following errors:

in function int main()
expected : before answer
break statement not within loop or switch
case statement 2 not within a switch statement
expected : before answer
break statement not within loop or switch and carries on for each choice in the switch statement. I can't see what is wrong with it.
I am compiling with Dev c++ 4.9.9.2 on Windows 7.
Here is the code:

//A calculator - this calculator performs basic addition, subtraction, multiplication and division tasks
#include <iostream>
#include <windows.h>
using namespace std;

int main()
{
float num1; //Calculator number input
float num2;
float answer;
int choice;

cout<< "Please input 2 numbers: \n";
cout<< "num1: \n";
cin>> num1;
cout<< "num2; \n";
cin>> num2;

cout<< "Please input 1 for add, 2 for subtract, 3 for mult, 4 for div: \n";
cin>> choice;
switch (choice) //Case statement allows person to choose from 4 choices for + - * and \
{ //Case 1 sets answer to be number 1 added to number 2 and prints results
case 1:
answer = num1 + num2;
cout<< answer;
system("pause");
break;

case 2:
answer = num1 - num2;
cout<< answer;
system("pause");
break;

case 3:
answer = num1 * num2;
cout<< answer;
system("pause");
break;

case 4;
answer = num1 / num2;
cout<< answer;
system("pause");
break;
default:
cout<< "Input error, incorrect choice. \n";

}

return 0;

}


See More: Case statement not within loop or switch

Report •

#1
September 18, 2010 at 09:57:57
Remove the braces in the switch block.
EDIT: I am an idiot.

Report •

#2
September 18, 2010 at 10:05:16
Am still getting the same messages after removing both { } from the switch statement.

Report •

#3
September 18, 2010 at 10:33:03
Gah, why am I trying to force bash case syntax in C++? (Probably because I'm working on a bash script, but it's not really an excuse.)

Ahem. I dumped your original code (with braces) into Dev-C++, and it says you have a semicolon (instead of a colon) on your "case 4" line.

Also, get rid of your comments, and it should compile fine. (The problem is because your comment line ends in a backslash.)


Report •

Related Solutions

#4
September 18, 2010 at 11:00:27
Thanks Razor! I hadn't noticed that mistake until I ran the program through several times. Also I removed the comments and it works now.
Cheers

Report •

Ask Question