3

Fairly new to programming here. I can't get my default code in the switch statement to work. I want it to display an error and exit as soon as any data input that's not in the range is entered. For some reason, it goes to the next cout line after the switch statement.

#include <iostream>
#include <math.h>
#include <iomanip>
using namespace std;

int main()
{
char choice;
const double P=8.00, A=10.50, B=12.50;
double t,w,price;

cout<<"\nPlease enter the state code: ";
cin>>choice;

cout<<"\nPlease enter the Parcel's weight in KG: ";
cin>>w;

switch (choice)
    {
    case 'P':
    case 'p':
        t=w*P;
        price=P;

    break;

    case 'A':
    case 'a':
        t=w*A;
        price=A;

    break;

    case 'B':
    case 'b':
        t=w*B;
        price=B;

    break;

    default:
        cout<<"Error. Please Re-enter. Exiting";

    break;

    }

cout<<setw(80)<<setfill('*')<<"*"<<endl;
cout<<"\nState code: "<<choice<<endl;
cout<<"Weight <KG>: "<<w<<endl;
cout<<"Price <RM>: "<<price<<endl;
std::cout<<std::fixed;
std::cout<<std::setprecision(2);
cout<<"Total Price <RM>: "<<t<<endl;
cout<<"\nThank you and Please Come Again"<<endl;
cout<<setw(80)<<setfill('*')<<"*"<<endl;

return 0;

}
Kon
  • 4,023
  • 4
  • 24
  • 38
ThePete
  • 33
  • 3

2 Answers2

6

If you want to end the program in your default case, you need to call exit(some_status)before the break. Otherwise, break just causes the switch statement to end and you continue right after the switch block.

Kon
  • 4,023
  • 4
  • 24
  • 38
2

You need to end your program after the error message. You can use either a call to exit() or a return statement.

user3344003
  • 20,574
  • 3
  • 26
  • 62