如何让 C++ 控制台程序退出?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4038302/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 14:20:59  来源:igfitidea点击:

How do I make a C++ console program exit?

c++exit

提问by rectangletangle

Is there a line of code that will terminate the program?

是否有一行代码可以终止程序?

Something like python's sys.exit()?

像python的东西sys.exit()

采纳答案by Benjamin Lindley

#include <cstdlib>
...
exit( exit_code );

回答by James McNellis

While you cancall exit()(and may need to do so if your application encounters some fatal error), the cleanest way to exit a program is to return from main():

虽然您可以调用exit()(如果您的应用程序遇到一些致命错误,可能需要这样做),退出程序的最干净的方法是从main()以下位置返回:

int main()
{
    // do whatever your program does

} // function returns and exits program

When you call exit(), objects with automatic storage duration (local variables) are not destroyed before the program terminates, so you don't get proper cleanup. Those objects might need to clean up any resources they own, persist any pending state changes, terminate any running threads, or perform other actions in order for the program to terminate cleanly.

当您调用 时exit(),具有自动存储持续时间(局部变量)的对象在程序终止之前不会被销毁,因此您不会得到适当的清理。这些对象可能需要清理它们拥有的任何资源、保留任何挂起的状态更改、终止任何正在运行的线程或执行其他操作,以便程序干净地终止。

回答by Bowie Owens

There are several ways to cause your program to terminate. Which one is appropriate depends on why you want your program to terminate. The vast majority of the time it should be by executing a return statement in your main function. As in the following.

有几种方法可以使您的程序终止。哪一个合适取决于您希望程序终止的原因。大多数情况下,它应该通过在主函数中执行 return 语句来实现。如下所示。

int main()
{
     f();
     return 0;
}

As others have identified this allows all your stack variables to be properly destructed so as to clean up properly. This is very important.

正如其他人已经确定的那样,这允许您正确销毁所有堆栈变量以便正确清理。这是非常重要的。

If you have detected an error somewhere deep in your code and you need to exit out you should throw an exception to return to the main function. As in the following.

如果您在代码深处检测到错误并且需要退出,则应该抛出异常以返回主函数。如下所示。

struct stop_now_t { };
void f()
{
      // ...
      if (some_condition())
           throw stop_now_t();
      // ...
}

int main()
{
     try {
          f();
     } catch (stop_now_t& stop) {
          return 1;
     }
     return 0;
 }

This causes the stack to be unwound an all your stack variables to be destructed. Still very important. Note that it is appropriate to indicate failure with a non-zero return value.

这会导致堆栈展开并销毁所有堆栈变量。还是非常重要的。请注意,使用非零返回值指示失败是合适的。

If in the unlikely case that your program detects a condition that indicates it is no longer safe to execute any more statements then you should use std::abort(). This will bring your program to a sudden stop with no further processing. std::exit() is similar but may call atexit handlers which could be bad if your program is sufficiently borked.

如果在不太可能的情况下,您的程序检测到表明不再安全执行任何语句的条件,那么您应该使用 std::abort()。这将使您的程序突然停止,不再进行进一步处理。std::exit() 类似,但可能会调用 atexit 处理程序,如果您的程序足够无聊,这可能会很糟糕。

回答by Oliver Charlesworth

Yes! exit(). It's in <cstdlib>.

是的! exit(). 它在<cstdlib>.

回答by Sydius

Allowing the execution flow to leave mainby returning a value or allowing execution to reach the end of the functionis the way a program should terminate except under unrecoverable circumstances. Returning a value is optional in C++, but I typically prefer to return EXIT_SUCCESSfound in cstdlib (a platform-specific value that indicates the program executed successfully).

允许执行流main通过返回值离开或允许执行到达函数的末尾是程序应该终止的方式,除非在不可恢复的情况下。返回值在 C++ 中是可选的,但我通常更喜欢返回EXIT_SUCCESS在 cstdlib 中找到的值(一个特定于平台的值,表示程序执行成功)。

#include <cstdlib>

int main(int argc, char *argv[]) {
  ...
  return EXIT_SUCCESS;
}

If, however, your program reaches an unrecoverable state, it should throw an exception. It's important to realise the implications of doing so, however. There are no widely-accepted best practices for deciding what should or should not be an exception, but there are some general rules you need to be aware of.

但是,如果您的程序达到不可恢复的状态,则它应该抛出异常。然而,重要的是要意识到这样做的影响。没有广泛接受的最佳实践来决定什么应该或不应该是例外,但有一些您需要注意的一般规则。

For example, throwing an exception from a destructor is nearly always a terrible idea because the object being destroyed might have been destroyed because an exception had already been thrown. If a second exception is thrown, terminateis called and your program will halt without any further clean-up having been performed. You canuse uncaught_exceptionto determine if it's safe, but it's generally better practice to never allow exceptions to leave a destructor.

例如,从析构函数抛出异常几乎总是一个糟糕的主意,因为被销毁的对象可能已经被销毁,因为已经抛出了异常。如果抛出第二个异常,terminate则调用 并且您的程序将停止而没有执行任何进一步的清理。您可以使用uncaught_exception来确定它是否安全,但通常更好的做法是永远不要让异常离开析构函数。

While it's generally always possible for functions you call but didn't write to throw exceptions (for example, newwill throw std::bad_allocif it can't allocate enough memory), it's often difficult for beginner programmers to keep track of or even know about all of the special rules surrounding exceptions in C++. For this reason, I recommend only using them in situations where there's no sensible way for your program to continue execution.

虽然您调用但未写入的函数通常总是可能抛出异常(例如,如果无法分配足够的内存,new则会抛出异常std::bad_alloc),但初学者程序员通常很难跟踪甚至了解所有异常围绕 C++ 异常的特殊规则。出于这个原因,我建议只在您的程序没有合理的方式继续执行的情况下使用它们。

#include <stdexcept>
#include <cstdlib>
#include <iostream>

int foo(int i) {
  if (i != 5) {
    throw std::runtime_error("foo: i is not 5!");
  }
  return i * 2;
}

int main(int argc, char *argv[]) {
  try {
    foo(3);
  }
  catch (const std::exception &e) {
    std::cout << e.what() << std::endl;
    return EXIT_FAILURE;
  }
  return EXIT_SUCCESS;
}

exitis a hold-over from C and may result in objects with automatic storage to not be cleaned up properly. abortand terminateeffectively causes the program to commit suicide and definitely won't clean up resources.

exit是 C 的保留,可能会导致无法正确清理具有自动存储的对象。 abortterminate有效地导致程序自杀,绝对不会清理资源。

Whatever you do, don't use exceptions, exit, or abort/terminateas a crutch to get around writing a properly structured program. Save them for exceptional situations.

无论您做什么,都不要使用异常、exit、或abort/terminate作为拐杖来绕过编写结构合理的程序。将它们保存在特殊情况下。

回答by Corgan

if you are in the main you can do:

如果你在主要你可以这样做:

return 0;  

or

或者

exit(exit_code);

The exit code depends of the semantic of your code. 1 is error 0 e a normal exit.

退出代码取决于代码的语义。1 是错误 0 ea 正常退出。

In some other function of your program:

在程序的其他一些功能中:

exit(exit_code)  

will exit the program.

将退出程序。

回答by Moberg

In main(), there is also:

在 main() 中,还有:

return 0;

回答by ConductedForce

This SO postprovides an answer as well as explanation why not to use exit(). Worth a read.

这个SO 帖子提供了一个答案以及为什么不使用 exit() 的解释。值得一读。

In short, you should return 0 in main(), as it will run all of the destructors and do object cleanup. Throwing would also work if you are exiting from an error.

简而言之,您应该在 main() 中返回 0,因为它将运行所有析构函数并进行对象清理。如果您从错误中退出,投掷也将起作用。

回答by Paul Sumpner

throw back to main which should return EXIT_FAILURE,

扔回应该返回 EXIT_FAILURE 的 main,

or std::terminate() if corrupted.

或 std::terminate() 如果损坏。

(from Martin York's comment)

(来自马丁约克的评论)

回答by Shadow

#include <cstdlib>
...
/*wherever you want it to end, e.g. in an if-statement:*/
if (T == 0)
{
exit(0);
}