C++ 默认值在开关语句中不起作用

c++ default not working in switch statement

本文关键字:不起作用 语句 开关 默认值 C++      更新时间:2023-10-16

这里编程相当新。我无法让 switch 语句中的默认代码正常工作。我希望它显示错误并在输入任何不在范围内的数据输入后立即退出。出于某种原因,它会转到 switch 语句之后的下一个cout行。

#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;
}

如果要在default情况下结束程序,则需要在break之前调用exit(some_status)。 否则,break只会导致 switch 语句结束,并且您在switch块之后继续。

您需要在

出现错误消息后结束程序。您可以使用对 exit(( 的调用或返回语句。