c++ - C++中的停止代码

标签 c++

如何阻止代码在 C++ 中运行?我有代码

#include <iostream>
#include <cmath>
using namespace std;
int main() {
    int total, sub, subc;
    cout << "What number would you like to start with? ";
    cin >> total;
        cout << "Enter in a number, 1 or 2, to subtract";
    cin >> sub;
    if (sub == 1) {
        total--;
        subc++;
        cout << "You subtracted one";
    }
    else {
        total = total - 2;
        subc++;
    }
    if (sub <= 0)
        cout << "YAY!";
}

我想插入一个停止代码并在 cout << "YAY!" 之后立即退出的东西 我该怎么做???

最佳答案

返回语句将结束 main函数和程序:

return 0;

预计到达时间:虽然正如@Mysticial 指出的那样,该程序确实会在 cout << "YAY!" 之后立即结束。行。

预计到达时间:如果您实际上是在 while 循环中工作,离开循环的最佳方式是使用 break声明:

#include <iostream>
#include <cmath>
using namespace std;
int main() {
    int total, sub, subc;
    cout << "What number would you like to start with? ";
    cin >> total;
    while (1) {
            cout << "Enter in a number, 1 or 2, to subtract";
        cin >> sub;
        if (sub == 1) {
            total--;
            subc++;
            cout << "You subtracted one";
        }
        else {
            total = total - 2;
            subc++;
        }
        if (sub <= 0) {
            cout << "YAY!";
            break;
        }
    }
}

关于c++ - C++中的停止代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9458408/

相关文章:

C++ 元编程 doxygen 文档

c++ - 对在 std::map 的查找/插入上使用可升级锁感到困惑

c++ - 模板中的数组和指针

c++ - 从 char* 缓冲区构造字符串时是否需要考虑编码 (UTF-8)

c++ - 全局常量对静态数据成员的初始化是否会导致未定义的行为?

c++ - 运算符(operator)覆盖错误

c++ - 如何在 addr2line 运行时从偏移量中的 backtrace_symbols() 解析 cpp 符号

c++ - 调试断言失败(_BLOCK_TYPE_IS_VALID)...此解决方案有效吗?

c++ - 使用返回类型作为派生类的指针

c++ - 以 C++11 风格进行类型转换的正确方法?