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

时间:2016-07-11 05:35:10

标签: 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,我该如何停止代码?

谢谢!

4 个答案:

答案 0 :(得分:1)

你必须在return后写:

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

这将停止代码。

答案 1 :(得分:1)

当您从return main()时,您的计划就会结束,因此您应该安排这件事发生。

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

答案 2 :(得分:1)

您可以像这样编写代码:

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 
}

答案 3 :(得分:1)

在C ++中使用return语句或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;
}