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

C++ 如果用户出错,如何停止程序?,c++,C++,我正在写一个程序,用户输入他有多少钱,如果低于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,就会说

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,我如何使代码停止

谢谢

您必须在以下时间之后写入返回:


这将停止代码。

当您从main返回时,程序将结束,因此您应该安排这样做


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

您可以这样编写代码:

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 
}

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

#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;
}
相反,如果使用退出功能,它将如下所示:

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

你是说退出这个项目吗?从主函数返回?应该使用if-else语句。是否要使用句号?然后写exit0;在if块中。@JoachimPileborg是的,类似这样的代码非常稀少,很难帮助我写返回0;?是的,正如这里解释的:@MiguelNunez:很高兴我能帮忙!返回退出失败;,或者返回EXIT\u SUCCESS;。我将其更改为返回0;。这是否表示成功?程序返回是否成功取决于退出状态是否用于控制执行环境中的某些内容。是,返回0;与return EXIT_SUCCESS;相同;。
#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;
}