0

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

#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???

Emile Cormier
  • 28,391
  • 15
  • 94
  • 122
Billjk
  • 10,387
  • 23
  • 54
  • 73

3 Answers3

4

A return statement will end the main function and therefore the program:

return 0;

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

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

#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;
        }
    }
}
David Robinson
  • 77,383
  • 16
  • 167
  • 187
1

try:

 char c;
 cin >> c;

This will wait until you hit enter before exiting.

or you can do:

#include <stdlib.h>
system("pause");
perreal
  • 94,503
  • 21
  • 155
  • 181
0

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

cout << "YAY!";

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

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

Knasterbax
  • 7,895
  • 1
  • 29
  • 23