c++ - 通过函数结束程序?

标签 c++

对于这样一个初学者的问题很抱歉,但是有没有办法通过 main 之外的函数来结束程序?我想根据用户输入结束程序。如果用户 cin 'no' 我希望程序终止。

char askStart(string question)
{       
    char response;

    do {

        cout << question << "(y/n): ";
        cin >> response;

    } while (response != 'y' && response != 'n');

    { 
        if (response == 'n') {

            cout << "\nVery well then....\n\n";

        } else {

            cout << "\nHere we go!\n\n";

        }

       return response; 
    }
}

最佳答案

是的,您可以通过调用 std::exit 随时结束程序:

#include <cstdlib>

void foo()
{
    std::exit(EXIT_SUCCESS);
}

事实上,从 main 返回值 n 的行为与调用 std::exit(n); 相同。

请注意,exit 会结束所有正在运行的线程,如果您没有明确加入它们,您可能会招致各种未定义或不良行为。

关于c++ - 通过函数结束程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27724895/

相关文章:

c++ - std::vector 等不必要地(错误地?)实例化嵌套模板参数类型

c++ - CodeBlocks 代码在 Visual Studio 中不起作用

c++ - 使用模板类型参数时出错

c++ - 处理多字节字符的字符串

.net - C++、.NET : Will this leak memory?

java - C++ 破坏了我的想法,如何信任自动垃圾收集器?

c++ - "int &temperature"与 C++ 中的 "int& temperature"相同吗?

c++ - 在段错误期间可以调用析构函数

c++ - 套接字 - 使用选择超时

C++ 继承的虚方法仍然使用基类实现