2

我目前有一个具有以下基本结构的程序

main 函数 -- 向用户显示菜单选项 -- 通过将用户输入传递给第二个函数 (input_validator) 来验证用户输入 -- 如果用户选择选项 1,则运行函数 1 等

function1,2,3,etc -- 用户请求输入,然后由 input_validator 验证 -- 如果 input_validator 返回 true,我们知道输入是好的

这是我的问题。我想允许用户在程序中的任何时候通过键入“0”退出。我计划使用 input_validator 中的一些基本代码来执行此操作(如果 input = 0 等)。

这看起来很简单,但有人告诉我,使用 quit() 会导致某些资源永远不会被释放 / 等等。我也不能简单地做一个“休息”——它会导致我的程序简单地返回到主程序功能。

有任何想法吗?

4

6 回答 6

4

exit()

正常终止进程,为终止进程执行定期清理。

首先,通过调用 atexit 注册的所有函数都按其注册的相反顺序执行。然后,关闭所有流并删除临时文件,最后将控制权返回给宿主环境。

于 2010-02-16T06:11:54.930 回答
4

一种可能性是通过抛出你在 main 中捕获的异常来实现,当你捕获它时,你退出程序。抛出异常的好处是它允许析构函数运行以清理已创建的对象,如果您直接从其他地方退出(例如,通过使用exit()),则不会发生这种情况。

于 2010-02-16T06:15:07.327 回答
3

很长一段时间以来,任何一种主流操作系统都不是这样。操作系统确保所有内核资源都被释放,即使程序没有明确这样做。从代码中的任何位置调用 abort() 或 exit() 都可以。

于 2010-02-16T06:16:02.833 回答
1

exit(int exitCode) - 在 stdlib.h / cstdlib 中定义 - 你可能想要 exit(0); // 正常终止。

于 2010-02-16T06:13:01.320 回答
0

exit() 不会调用您的析构函数,因此您可能需要考虑使用异常处理程序。

如果您有打开但未刷新的文件之类的东西,操作系统将关闭文件句柄,但不会刷新任何未写入的数据。

于 2010-02-16T07:49:01.063 回答
0

You have to design your menu system so that a status can be passed back to the previous method, unwinding until code in the main function is executed. Similar issues apply to back or previous screen buttons.

Taking a step back and looking at the Big Picture, the unwinding technique looks very similar to C++ exception handling strategy. I suggest using exceptions for cases that don't follow the normal flow of execution, such as main menu, and previous menu.

Try it out.

于 2010-02-16T17:53:19.213 回答