在 C++ 中停止代码

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9458408/
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-27 12:51:32  来源:igfitidea点击:

Stop Code in C++

c++

提问by Billjk

How do you stop the code from running in C++? I have the code

你如何阻止代码在 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!";
}

and i want to insert a thing that just stops the code and exits right after cout << "YAY!"how do i do that???

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

回答by David Robinson

A return statement will end the mainfunction and therefore the program:

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

return 0;

ETA: Though as @Mysticial notes, this program will indeed end right after the cout << "YAY!"line.

ETA:尽管正如@Mysticial 所指出的那样,该程序确实会在该cout << "YAY!"行之后立即结束。

ETA: If you are in fact working within a while loop, the best way to leave the loop would be to use a breakstatement:

ETA:如果您实际上在 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;
        }
    }
}

回答by perreal

try:

尝试:

 char c;
 cin >> c;

This will wait until you hit enter before exiting.

这将等到您在退出之前按 Enter 键。

or you can do:

或者你可以这样做:

#include <stdlib.h>
system("pause");

回答by Knasterbax

As David Robinson already noted, your example makes no sense, since the program will stop anyway after

正如大卫罗宾逊已经指出的那样,你的例子没有意义,因为程序无论如何都会停止

cout << "YAY!";

cout << "YAY!";

But depending on the scenario, besides breakand return, also exit()might help. See the manpage:

但是根据情况,除了breakreturn之外,exit()也可能有所帮助。请参阅联机帮助页:

http://www.cplusplus.com/reference/cstdlib/exit/

http://www.cplusplus.com/reference/cstdlib/exit/