如果用户出错,如何停止程序

How do I stop a program if the user gets something wrong?

本文关键字:何停止 程序 用户 出错 如果      更新时间:2023-10-16

我正在编写一个程序,用户在其中输入他有多少钱,如果低于 50,它会说"

Sorry not Enough

我希望程序到此结束。

这是我编写的代码:

cin >> money;
if (money <= 50) {
    cout << "Sorry not enough" << endl;
}
cout << "Here are the items you can buy" << endl;
int a = 50;
int b = 200;

当然,这不是我编写的全部代码。如果这个人写的数字小于 50,我如何让代码停止?

谢谢!

你可以像这样编写代码:

cin >> money;
if (money <= 50) {
    cout << "Sorry not enough" << endl;
}
else {
   cout << "Here are the items you can buy" << endl;
   // Operations you want to perform 
}

当你从main() return时,你的程序就结束了,所以你应该安排这样做。

或者你可以调用exit(),但这是一个坏主意,因为析构函数不会运行。

使用 return 语句或 C++ 中的 exit() 函数将退出程序。您的代码如下所示:

int main()
{
cin >> money;
if (money <= 50) {
    cout << "Sorry not enough" << endl;
    return 0;
}
cout << "Here are the items you can buy" << endl;
int a = 50;
int b = 200;
}

相反,使用 exit() 函数,它看起来像:

#include<stdlib.h> //For exit function
int main()
{
cin >> money;
if (money <= 50) {
    cout << "Sorry not enough" << endl;
    exit(0);
}
cout << "Here are the items you can buy" << endl;
int a = 50;
int b = 200;
}
你必须在以下

之后写return

cout << "Sorry not enough" << endl; 

这将停止代码。