c++ default not working in switch statement

The*_*ete 3 c++ switch-statement

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;

}
Run Code Online (Sandbox Code Playgroud)

ODY*_*Kon 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.

  • 由于主要是这样,所以也可以`返回EXIT_FAILURE`来代替调用`exit`。 (4认同)