如果用户出错,如何停止程序
How do I stop a program if the user gets something wrong?
我正在编写一个程序,用户在其中输入他有多少钱,如果低于 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;
这将停止代码。
相关文章:
- 程序在使用 system() 启动另一个可执行文件时停止
- 循环通过网格获取温度,但不知道如何告诉程序停止循环
- 从Raspberry Pi / Linux上的Python脚本运行和停止C++程序
- 变量停止程序的C 增量
- 使用任意键(c ++)停止程序
- 当不活动 /焦点中时,如何停止C / C 程序检查键盘
- 如何停止C 程序在等待条件时关闭时崩溃
- 如何从Linuxos中的Python脚本运行/停止C程序
- C++中的代码将不接受否并停止程序
- destroyWindow(来自opencv)关闭所有窗口并停止c ++程序
- 如果函数C++中满足条件,则完全停止程序
- 如何使用用户的输入停止程序的某个部分?
- 如何在开关语句后停止程序关闭
- 需要帮助以在未经用户同意的情况下停止程序终止
- connect() 函数停止程序
- GDB 断点未停止程序(项目符号物理库中的断点)
- Windows 无法分配内存并停止程序?
- GDB和NS2:如何在某个函数调用时停止程序
- 在一定时间后停止程序执行的更好方法
- 如果用户出错,如何停止程序