c++ - 从 C++ 函数安全关闭程序
问题描述
我想制作一个程序,在读取用户输入文件后执行一些数学运算。
在读取过程中(一个函数),我想检查文件中的用户语法是否正确,否则我想关闭程序,以便用户可以相应地修改文件(s=并再次运行它。
结构将是这样的:
int main(int argCount, char *args[])
{
std::string fileName = "PathOfFile";
int a = GetUserInput(fileName, variableName);
int b = GetUserInput(fileName, variableName);
// Other functions will be placed here
return 0;
}
int GetUserInput(std::string filename, std::string variableName)
{
// Some routine to read the file and find the variableName
// Some routine to check the syntax of the user input.
// Let us assume that the integers are to be fined as: variableName 1;
// and I want to check that the ; is there. Otherwise, shutdown the program.
}
如何从该功能安全地关闭程序GetUserInput
?是否有任何 C++ 表明程序必须结束并退出?
解决方案
有许多不同的方法可以做到这一点,不同之处主要在于风格、个人偏好以及您熟悉 C++ 库的哪些部分。
- 解析函数只是调用
exit()
. int
该函数不返回值设置,而是将指针或对int
值的引用作为附加参数并设置它(如果有效)。bool
相反,该函数返回 a以指示它是否解析了有效设置。main()
检查返回的bool
值,以及它本身return
的 frommain()
,结束程序。- 解析函数返回 a
std::optional<int>
,而不是返回 astd::nullopt
以指示解析失败。main()
检查返回的值,以及它本身return
的 frommain()
,结束程序。 - 解析函数抛出一个被捕获的异常,
main
异常处理程序return
来自main
。
每个替代方案都有其自身的优点和缺点。您可以自行决定哪种方法最适合您的程序。
推荐阅读
- java - How to identify the missing type id in Jackson error?
- php - 显示来自其他域的图像而不显示域名 - PHP
- haskell - mapM 中的所有 do 块都在 do 块内的主要计算之前执行
- python - 如何访问托管在 docker 中的烧瓶应用程序?
- java - Url Problem while Developing on Localhost and deploy on Remote Virtual Server
- javascript - How to write negative binary number?
- python - 如何在scrapy中加入多处理
- java - 如何使按钮方形边框适合图像圆形边框
- java - 在 Netty 处理程序中管理 CompletionStage
- javascript - Python GEE 从 Landsat 图像中提取特征收集时间序列